Enhancing one's comprehension of precompiling JavaScript

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

As I delve deeper into the inner workings of JavaScript running on the machine, I stumbled upon this code snippet. Despite my best efforts, I am perplexed as to why the final alert displays 1 instead of 10. If anyone could shed some light on how the JavaScript virtual machine processes these lines of code, I would greatly appreciate it. Thank you!

Answer №1

The reason for this behavior is function declaration hoisting:

var x = 1;
function y(){
  function x(){} // The engine moves this function declaration up
  x = 10; 
  return;
}
y();
alert(x); // Since the local variable x was reassigned, not the global one, it remains 1

Answer №2

I am puzzled as to why the final alert shows a value of 1 instead of 10.

This discrepancy occurs due to the foo variable within the function bar:

foo = 10;

...being associated with the function declaration later in that same function:

function foo(){}

...rather than the foo variable outside of that function. Specifically, this is referencing:

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

The reason for this behavior can be attributed to two factors:

  1. Function declarations are immediately processed upon entering the containing scope (in this case, the call to bar), before any step-by-step execution of code within the function. This phenomenon, sometimes referred to as "hoisting," ensures that all declarations are handled beforehand regardless of their placement in the code.

  2. Function declarations effectively create variables with identical names as the functions themselves. Therefore, the foo referenced in the function declaration acts as a variable with that name - thereby allowing assignment of new values to these "variable-like things."

When the provided code runs, here's the sequence of actions performed by the JavaScript engine:

  1. Creates a variable named foo with an initial value of undefined.

  2. Defines the bar function, registering it as an in-scope symbol within the current context and associating it with the function definition.

  3. Begins executing the code step-by-step within this scope.

  4. Sets the value of foo to 1.

  5. Invokes the bar function.

  6. Establishes the foo function relevant to the bar call, creating it as an in-scope symbol during the function invocation.

  7. Initiates the step-by-step processing within this nested scope.

  8. Assigns the value 10 to the local foo, which previously referenced the function itself.

  9. Exits from the function.

  10. Executes the alert function using the foo within this specific scope, still holding the original value of 1.

Further insights into this intricate process can be found in Section 10.4.3 of the ECMAScript specification along with its related sections.


* "variable-like thing": In JavaScript, every execution context (comprising the global context and all contexts resulting from function calls) maintains a binding object to manage various identifiers and their corresponding values within that specific context. The binding object incorporates properties for each variable, function declaration, and other essential elements like the arguments pseudo-array and the function name referring back to itself. Consequently, changing the value of foo within bar overrides the reference to the foo function declared inside bar rather than modifying the outer-scoped variable. Essentially, foo behaves akin to a local variable within bar due to the function declaration.

Answer №3

This topic relates to a programming concept known as hoisting. When you define a function using function foo, it is basically just another way of writing var foo = function ... So, within the bar function, the name foo actually refers to a local variable that shadows the outer foo variable. Initially, this foo is a function, but it later gets redefined as the number 10.

With hoisting, the name foo is "reserved" and scoped during the parsing phase before the code is executed. In essence, it operates as follows:

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

Therefore, it doesn't overwrite the outer variable at all.

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

Using Vue to make a REST API call in a JavaScript file

I have been trying to convert an Axios API call from a Vue page into a standalone module that can be reused multiple times in my app. Unfortunately, all my attempts so far have failed and I'm not sure if it's because I lack experience working wit ...

How to dynamically apply the orderBy filter in AngularJS

Attempting to input ordering criteria from a text box and dynamically order the content. The current code is functioning properly, but when attempting to change: orderBy:'age' to orderBy:'{{criteria}}' the functionality breaks. Her ...

An error message 'module.js:557 throw err' appeared while executing npm command in the terminal

Every time I try to run npm in the terminal, I encounter this error message and it prevents me from using any npm commands. This issue is also affecting my ability to install programs that rely on nodejs. $ npm module.js:557 throw err; ^ Error: Cannot ...

Leveraging jQuery.ajax() for retrieving c# WebMethod data triggers the error message of 'Unidentified Web Method'

I am diving into the world of jQuery.ajax() for the first time to call a WebMethod. Despite my efforts searching on stackoverflow and Google countless times, I seem to be stuck in a cycle of trial and error with random solutions. It's reached a point ...

Can someone help me understand why this AJAX script is returning a status code of 404?

After getting involved with AJAX and utilizing the MAMP web server, I decided to work on a simple script to test its functionality. My attempt led me to investigate using the status property of XMLHttpRequest(); As it turns out, the issue I encountered was ...

Glitchy/Crazy CSS3 Animations

Currently, I am developing a website at . One of the features I have implemented is CSS3 transitions for route changes, but this feature only works in Chrome. Here's how the animation works: I apply the .preanimate class to rotate the phasing out di ...

When utilizing "Koa-Rewrite," an AssertionError occurs stating that app.use(rewrite) necessitates a generator function

I am currently working with Koa@1 and koa-rewrite@1 to implement a specific functionality. rewritelogic.js const rewrite = require('koa-rewrite'); function rewriteLogic(){ rewrite('/english/experience/dev1', '/english/experienc ...

Prevent selection of specific weekdays in Kendo grid calendar

When editing a record in a Kendo grid with a date field, is there a way to only allow the selection of Monday and disable all other days of the week? ...

The jQuery plugin embedded in the Joomla 3.2 module fails to load or function properly

Seeking help with a JavaScript issue on my Joomla website. I'm not an expert, so please bear with me. I am using a regular plugin (not a Joomla specific one) to display my portfolio. It should work like this: ... black.html This is how it shouldn&a ...

I am having trouble retrieving any data when using jQuery to post JSON data

I am struggling with some HTML and JavaScript code. Here is what I have: <html> <head> </head> <body> <script src="view/backoffice/assets/plugins/jquery/jquery-1.11.1.min.js" type="text/javascript"></sc ...

Choose the initial selection from a dropdown menu using AngularJS

I am facing a minor issue where I want the first element in my select dropdown to be displayed properly rather than just a blank space. Below is the code snippet I am currently working with: <select style="border-radius: 4px;" class="form-control" ng- ...

Storing and Retrieving Cookies for User Authentication in a Flutter Application

I am currently working on developing a platform where, upon logging in, a token is created and stored in the cookie. While I have successfully implemented a route that stores the cookie using Node.js (verified in Postman), I encounter issues when attemptin ...

Guide on creating a similar encryption function in Node JS that is equivalent to the one written in Java

In Java, there is a function used for encryption. public static String encryptionFunction(String fieldValue, String pemFileLocation) { try { // Read key from file String strKeyPEM = ""; BufferedReader br = new Buffer ...

Send an ArrayList to jQuery Flot

Good day. Apologies for any language barriers as English is not my first language. I am a novice in [see tags] and I have a web application that gathers a date and a serial number to execute a SQL query. The query returns some data (measurement values an ...

Using TypeScript, pass an image as a prop in a Styled Component

I am facing an issue with the code below that is supposed to display the "NoBillsLaptopPNG.src" image on the screen, but for some reason, the image is not showing up. The images are being imported correctly, so I'm unsure why the image is not appeari ...

Transferring JavaScript to PHP

I have a challenge where I need to pass a string stored in a variable to a MySQL table using PHP. Currently, my workaround involves using a hidden <input>. I assign the variable value to it and submit it through a form. It works, but it's not e ...

JavaScript for beginners: show a specified amount of search results and insert a loading indicator at the end

Currently, I have a website that retrieves data from my database using a PHP query. However, the issue I am facing is that there are over 300 entries in my database, resulting in an excessively long displayed page. My main question: How can I restrict ...

javascript if condition not executing properly

I am struggling with my random number generator that should generate numbers between 5 and 15. I am trying to change the position of the 'chest' div based on the number generated by the computer, but for some reason it is not working as expected. ...

What is the best way to insert a chart into a div using *ngIf in Angular?

I just started using chart.js and successfully created the desired chart. However, when attempting to implement two tab buttons - one for displaying tables and the other for showing the chart - using *ngIf command, I encountered an error: Chart.js:9369 F ...

Using JavaScript to create an image slider

My image slideshow with prototyping is not working properly and I am struggling to fix it. I have tried binding the setInterval function but it's not working. I also attempted to wrap it, but that didn't work either. What should I do to solve thi ...