Declaring a function within a conditional statement

I recently came across a code sample in the book You Don't Know JS: Scope & Closures that is puzzling to me.

"Function declarations that appear inside of normal blocks typically hoist to the enclosing scope, rather than being conditional as this code implies:"

foo(); // "b"

var a = true;
if (a) {
   function foo() { console.log( "a" ); }
}
else {
   function foo() { console.log( "b" ); }
}

What does it mean? How is it even possible? Is the conditional not working?

Answer №1

The phenomenon occurs due to the way function declarations are elevated to the top of the file by the JavaScript parser, a process known as hoisting. As a result, the final declaration of foo takes precedence over the initial one when they are hoisted.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

ES6 import of CSS file results in string output instead of object

Too long; Didn't read I'm facing an issue where the css file I import into a typescript module resolves to a string instead of an object. Can someone help me understand why this is happening? For Instance // preview.ts import test from './ ...

Understanding the Typescript Type for a JSON Schema Object

When working with JSON-schema objects in typescript, is there a specific type that should be associated with them? I currently have a method within my class that validates whether its members adhere to the dynamic json schema schema. This is how I am doing ...

Issues with utilizing jQuery AJAX for form submissions

I am currently customizing a webpage to fit the specific requirements of a client using a template. The page contains two contact forms which are being validated and sent to a PHP file via AJAX. One of the forms is standard, while the other one has been mo ...

Creating form inputs dynamically in HTML and then sending them to a PHP script programmatically

On my webpage, users can click a button to add new form inputs as needed. However, I'm running into an issue trying to access these new inputs in the PHP file where I submit the data. Here is the code snippet for the button within the form on the pag ...

Even though the onSubmit attribute is set to false in the HTML form, it still submits

I've been struggling with a form that just won't stop submitting, no matter what I do. I have checked similar questions on SO, but none of the solutions seem to work for me. It's frustrating because it's such a simple task. The reason w ...

Explain the inner workings of the setTimeout() function in JavaScript

My goal is to create a line in my code by placing points according to the line equation and adding a 100 millisecond delay before each point is displayed. However, when I try to run the code, it seems to wait for some time and then displays all the points ...

Is it feasible to link an Angular property value to the value of an HTML data attribute?

Can an Angular property value be bound to a data attribute on a template element? <h1 data-name="{{name}}">Hello from {{ name }}!</h1> Example Link After running the code, it results in the following error: Error in src/main.ts (11: ...

Using jQuery to select the child element of the parent that came before

Recently, I've been experimenting with creating animations using CSS and jQuery. While it has been successful so far, I'm now looking to take it a step further. Specifically, I want information to appear on top of an image when the user clicks on ...

Updating or removing fullCalendar events in Symfony

I'm struggling to figure out how to update or delete fullcalendar events in my Symfony project. When adding a new event, I open a modal window with a form for submitting the event and inserting it into the database. This is my working controller: $ ...

Modify the width measurement from pixels to percentage using JavaScript

Looking for some help with a content slider on my website at this link: . I want to make it responsive so that it adjusts to 100% width. I managed to make it responsive by tweaking some code in the developer tools, but now I'm stuck. The bottom two p ...

Exploring Ngu-Carousel in Angular 7: Importing JSON data for a dynamic display

After attempting to import data from JSON and display it using ngu-carousel, I encountered an error. The error shows "length of undefined" Subsequently, when I try to click on the previous/next button, another error appears. This error states "innerHTML ...

In Javascript, the DOM contains multiple <li> elements, each of which is associated with a form. These forms need to be submitted using AJAX for efficient

I have a list element (ul) that includes multiple list items (li), and each list item contains a form with an input type of file. How can I submit each form on the change event of the file selection? Below is the HTML code snippet: <ul> ...

Why is my React component not updating after changing the state using Set State?

Uncovering the elusive problem seems impossible. Despite state changes, the component remains unrerendered. Here's the code: export const InterestsPupup: React.FC = ({interests, title, buttonText}) => { const [activeItems, setActiveItems] = useSt ...

Is there a way to track the amount a user scrolls once they have reached the bottom of a page using Javascript?

It's a popular UI pattern on mobile devices to have a draggable element containing a scrollable element. Once the user reaches the end of the scrollable content, further scrolling should transition into dragging the outer element. For example, in this ...

What could be the reason for Spawn() not being invoked?

After working with node.js and express for some time, I have encountered a persistent bug in my code. In my service file, there is a resolved Promise where I call spawn(), but for some reason, the spawn code never gets executed (or if it does, ls.on(' ...

Extract information from an external website using AJAX in Laravel

On my cart page, I utilize ajax to retrieve destination information from the user and provide them with shipping options to calculate their shipping cost. While everything is functioning properly, one issue remains: I am unsure of how to iterate through t ...

Linking the location of the pop-up to the currently selected text box

I am currently experimenting with setting the top and left values relative to the selected_element (which is active at the time of triggering the popup) in a manner similar to a tooltip. I attempted to use $().position() in combination with jQuery, but it ...

React / Next.js Rendering Problem, Data Discrepancy Between Client and Server

A new feature has been added to a webpage where an image background and a city name are displayed on top of it. The data file that generates these image backgrounds and city data consists of a standard array of objects. The challenge lies in dynamically l ...

React JS component experiencing issues with Material UI modal functionality

Attempting to reproduce the material ui modal example has proven to be a challenge for me. Initially, I encountered an error stating "Cannot read property 'setState' of undefined" which I managed to resolve. However, even after resolving this iss ...

Learn how to efficiently import data into d3.js from several JavaScript arrays, and create a dynamically updating chart without the need to refresh the page

I currently have two arrays: one is a list of numbers called nums, and the other is a list of strings titled places. For example: nums=[1,2,3,4,5] places = ["house","gym", "work", "school", "park"] Both arrays are the same length. I am looking to crea ...