When a global variable is defined after a return statement within a function declaration, it does

Check out this Javascript code snippet: http://jsfiddle.net/ramchiranjeevi/63uML/

var foo = 1;
function bar() {
    foo = 10;
    return;
    function foo() {}   
}

bar();
console.log(foo);  // should return 10, but returns 1

It's interesting to note that even though the variable is overwritten within the bar() function, the log still prints the original value of 1 instead of 10.

Answer №1

Function declarations are "hoisted", which means they are moved to the top of the scope.

As a result, a new context for foo is created within the local scope. Any later assignment of 10 will affect this localized scope and not the variable from the parent scope.

A similar behavior can be observed when declaring a block-local variable named foo using the var keyword:

var foo = 1;
function bar() {
    var foo = 10; // effectively creates a function named foo in this scope
    return;
}

bar();
console.log(foo); // output: 1

http://jsfiddle.net/GRMule/8F5K3/

Another example elucidating this concept:

var foo = 1;
function bar() {
    console.log(foo); // due to hoisting, "function" will be the output
    foo = 10;         // overwrites the block-local foo
    return;
    function foo () {} // hoisted to the top of this scope, creating a new "foo" context
}

To prevent hoisting, you can use the var method while declaring functions, though it's recommended to maintain code readability by avoiding reusing names like this:

var foo = 1;
function bar() {
    console.log(foo); // undefined
    foo = 10;
    return;
    var foo = function () {};
}
bar();
console.log(foo); // 1

http://jsfiddle.net/znrG2/

Using the var word in a scope block causes the existence of that local context to be hoisted, not the value. Variables with the same name from the parent scope won't be accessible or affected in the current scope.

Functions and variables declared using this, such as this.foo = function () {};, do not hoist. Details here: http://jsfiddle.net/8F5K3/3/

Declaring functions or variables with this doesn't overwrite variable contexts from the parent scope. This can be utilized to circumvent this behavior when needing to reuse the name "foo":

var foo = 1;
function bar() {
    console.log(foo); // 1
    foo = 10;
    return;
    this.foo = function () {};
}
bar();
console.log(foo); // 10

http://jsfiddle.net/znrG2/1/

Additional Resources

Answer №2

Understanding JavaScript hoisting behavior is crucial. You can find more information about it in this resource. In the scenario you presented, the script is executed as follows:

var foo = 1;
function bar() {
    function foo() {}
    foo = 10;
    return; 
}

bar();
console.log(foo);

This happens because:

Function declarations and variable declarations are always effortlessly moved (“hoisted”) to the top of their containing scope by the JavaScript interpreter

In your case, when you set foo = 10;, you are actually assigning to the local variable. This explains why the global variable remains unchanged.

Answer №3

When the function foo() is defined within the local scope of bar(), any redefinition of foo() within bar() will only affect the local scope variable and not the global scope.

Answer №4

function bar() {
  const baz = 10;  // let's create a local variable named "baz"
  return;    // the return value of this function is undefined
  function buzz() {}   // we define a function called "buzz" inside the bar function, which means that the global variable "baz" does not change.
}

Therefore, the global variable baz remains unaffected.

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

Adjust the cursor in a contenteditable division on Chrome or Webkit

Is there a way to set the caret position in a contenteditable div layer? After trying different methods and doing some research online, I finally found a solution that works in firefox: function set(element,position){ element.focus(); var range= w ...

Loading screen featuring an outlined blueprint of design elements

Can anyone identify the technology or language used to create the preloader screen on websites like the one shown in this link? The elements have a sweeping shine effect while loading. This style of preloader screen can be seen on popular websites such as ...

Iterating through the sorted list in reverse order, retrieving the text of each list item

Is there a way to navigate through an ordered list, extract and return the text based on a scenario where the user clicks on an li element like Cat 1-2? The goal is to concatenate all parent li's text into either a string or an array. If an array is u ...

Unable to locate template or render function for Vue Draggable Next component

Looking to incorporate Vue Draggable Next into a Vue 3 example page but encountering some challenges. I've attempted to follow the instructions in the repository. However, I ran into issues when importing the Vue Draggable Next component and had to re ...

Tips for implementing multiple selectors in YUI

Is there a way to use multiple selectors in YUI (YUI 2) similar to jQuery? $('h1, h2, el1, el2, .content, .title').css('color', 'red'); How can I achieve the same in YUI without having to individually add classes using YAHOO ...

The issue with implementing simple getElementsByClassName JavaScript in the footer of a WordPress site persists

I am facing an issue with a 1-liner JavaScript code in the footer where getElementsByClassName function doesn't seem to work for tweaking style attributes. The text "Hello World" is displaying fine, so I suspect it might be a syntax error? Here' ...

How to use node.js to add JSON data to a JSON file without using an array?

I'm trying to update a JSON file without using an array with FS. The desired format of the file should be: { "roll.705479898579337276.welcomemessage": "There is a welcome message here", "roll.726740361279438902.welcome ...

Automatically assigning IDs to all elements on an Angular webpage

We are currently developing an enterprise web application and have brought on board an e2e test engineer to automate tests. The test engineer has requested that we assign IDs to all elements in our pages. Is there a tool or method available to automatical ...

Enhanced User Experience Through Triggered Content Recommendations based on Scrolling Patterns

When a user scrolls beyond a certain point on a webpage, I would like a recommended content popup to slide out from the right side at the bottom of the page. An excellent example can be seen on USAToday where a blue recommended box appears as you scroll d ...

Encountering an issue when attempting to save JSON data in the database: unable to convert object into a string

To summarize, my data is stored in Javascript: JSONdata = { name: form.name.value, address1: form.custa.value, address2: form.custa2.value, postcode: form.custpc.value, order: fullorder, cost: document.getElementById('total&ap ...

What is the process of nesting an array of objects within an existing object, and how can additional objects be added to the array if it already exists?

I have a JSON file named questions.json containing an array of objects structured like this: { "id": "2", "ques": "here is my second code ?", "quesBrief": "I can't seem to find it too.", "hashes": "#javascript , #goodlord", "author": "slowde ...

The sequence of CSS and deferred JavaScript execution in web development

Consider this scenario: you have a webpage with a common structure in the <head>: <link rel="stylesheet" href="styles.css"> // large CSS bundle <script defer src="main.js"></script> // small JS bundle with defer attribute There is ...

Repetitive attempts have led to the cancellation of the AJAX and PHP petition statuses

Whenever I click the button, I am trying to update a MySQL table using AJAX jQuery. Unfortunately, I am encountering a problem where the AJAX jQuery does not work properly sometimes. It starts off fine, but after a certain number of attempts, it stops work ...

What is the process for removing an added message using jQuery after it has been appended by clicking the same button?

https://i.stack.imgur.com/YsmKZ.pnghttps://i.stack.imgur.com/dW2lo.pngI have searched extensively through previously asked questions without success. My goal is to remove the previous appended message when the submit button is clicked again. This functiona ...

initiating a submission upon the occurrence of an onchange event on an input field of type "file"

I have encountered an issue while trying to submit a form using the onchange event of an input element with type file. The problem is that it submits an empty form even when a file has been chosen. Here is the code snippet: var form = document.createElem ...

JavaScript was unable to locate the requested URL on the server

After successfully deploying and accessing the URL using Firebase's hosting feature, everything seems to work fine. However, when I try to access a specific endpoint like this: https://*******.web.app/api/send, I encounter the following error message: ...

Unlocking the power of RXJS by de-nesting subscriptions

Trying to resolve the nested subscription issue has become a time-consuming puzzle. I've experimented with mergeMap, flatMap, and switchMap without success. Unfortunately, the examples I've come across don't quite fit my needs, leaving me wi ...

Instructions for outputting a string to the console in Javascript

I am looking for a versatile method to write a string to standard output in a portable manner, without automatically adding newlines at the end. I prefer it to utilize UTF-8 encoding and be compatible with: jrunscript (from any JDK) Rhino node.js Curren ...

Render multiple checkboxes with values from an array of objects passed as a prop to a child component using a v

I am facing an issue with my Vue components 'Parent' and 'Child'. Each child component has a checkbox with a :checked prop. In the Parent component, I iterate through an array of objects and pass props to the child. Although I can emit ...

Ways to calculate the memory utilization of a JavaScript object

Suppose I want to compare the efficiency of storing bits of a static canvas/image with Alpha more or less than 0.5 using an "array of array of number" versus an "array of string," which would be better in terms of memory usage and speed? var c = $('m ...