Can you please explain the distinction between the statements var a = b = 2 and var a = 2; var b = 2;

Whenever I try to declare a variable within a function, I encounter an issue.

var b = 44;
function test(){
    var a = b = 2;
}

However, the following code works without any problems:

var b = 44;
function test(){
    var a;
    var b = 2;
}

The global variable b is being overridden by the local one.

I have not been able to locate any documentation explaining this behavior.

Is there any official documentation addressing this issue?

Demo: http://jsfiddle.net/uq4nxk1k/1/

Answer №1

If you're looking for documentation, I'm not sure where to find it. However, let me explain the result you received:

Local > Global

When you declare a global variable, it can be accessed anywhere in your file. In the "test()" function, when you write:

var a = b = 2;

You are creating a new variable 'a' that takes the value of the global variable 'b' and simultaneously changes the value of 'b' to 2 - effectively overriding its value.

Similarly, when you write (inside 'test()'):

var a, b; 

or

var a; 
var b;

You are declaring two variables that are local to your function. When you assign a value to 'b', due to the principle of local being greater than global, you may encounter two scenarios:

  1. If you console.log(b) inside 'test()', you will get 2.
  2. If you console.log(b) outside 'test()', you will get 44.

Declaration != Assignment

Remember:

  • 'var a, b;' is a declaration.

  • 'a = b = 25;' is an assignment (essentially a double assignment).

  • 'var a = b = 25' combines declaration and assignment into one step.

I hope this explanation helps! Feel free to ask if anything is unclear or if you need further clarification. :)

Answer №2

let within a function's scope does not overwrite variables declared in an outer scope. Allow me to clarify the functionality of your exam() method:

// these are global variables:
let x = "out";
let y = "out";
let z = "out";
let u = "out";
let v = "out";
let w = "out";


function exam() {
    // the next line is equivalent to
    // let x; let y; z = "in";
    let x, y, z = "in"; 
    // the local variable y is set to "in"
    y = "in";
    // this translates to:
    // declare a local variable u which points to global v which points to global w
    // and assign them all the value "in"; hence only global v and global w get updated to "in";
   // *edited version: w = "in"; v = w; let u = v;
    let u = v = w = "in";
    // declare a local variable z and give it the value "in"
    let z = "in";
}
exam();
// when back in the global scope, x, y, z, u and v remain unchanged
// thus x == "out", y == "out", z == "out", u == "out", and v == "out"
// however, w == "in" and v == "in" due to modifications made by the exam() method

Answer №3

It's important to remember

When you assign primitive values like this:

var a = b = 2;

It is the same as:

var b = 2;
var a = b;

Both a and b will have the value of 2.

However, if you assign objects instead of primitive values:

var a = b = [1,2,3,4];

This means:

var b = [1,2,3,4];
var a = b;

This indicates that both a and b are referencing the same object. Therefore, any changes made to b will also affect a, and vice versa:

a.push(5); 
// a <--- [1,2,3,4,5] 
// b <--- [1,2,3,4,5] !! Be cautious! Changes made to b affect a too

Remember: Using a shorthand a = b = c = value assigns the same value to all variables. But when dealing with object assignment, they share the same reference pointing to a value. Always keep this in mind.

So for object assignment, this statement:

var a = b = [1,2,3,4]; // changing a WILL impact b

does not create the same effect as

var a = [1,2,3,4]; var b = [1,2,3,4]; // altering a won't affect b

Answer №4

One reason for this issue is that when you define variables within a function, they may not be accessible to $(".resultg").text("g = " + g);

However, in the line var d = e = f = "in";, a new local variable "d" is created which is set equal to global variables e and f, with the value "in". Since e and f are global, only in this instance will the reassignment to "in" be picked up by $(".resultg").text("g = " + g);

Answer №5

The question may not seem strange, and the answer is actually quite simple. It all boils down to understanding the concept of global variables.

// The following a,b,c,d,e,f,g are global variables

var a = "out";
var b = "out";
var c = "out";
var d = "out";
var e = "out";
var f = "out";
var g = "out";

Now, a,b,c,d,e,f,g have been assigned the value 'out'

If you attempt to alert any of them, it will display as 'out'

// Your function starts here

function test() {
    var a, b, c = "in"; // Here a,b,c are local variables and do not override the global variable values
    so this statement becomes meaningless when trying to print values from outside this function

    b = "in"; // Here lies the trick and confusion begins as b is actually a local variable created in the test function, not global
    Therefore, changing its value here will not affect the global one

    var d = e = f = "in"; // The same scenario applies here with e and f being global while d is local
    If we were to print the global variable values, we get:
    a=out
    b=out
    c=out
    d=out
    e=in
    f=in
    g=out

    var g = "in";

    Since this is also a local variable, the result will be:
    a=out
    b=out
    c=out
    d=out
    e=in
    f=in
    g=out
}

test();

$(".resulta").text("a = " + a);
$(".resultb").text("b = " + b);
$(".resultc").text("c = " + c);
$(".resultd").text("d = " + d);
$(".resulte").text("e = " + e);
$(".resultf").text("f = " + f);
$(".resultg").text("g = " + g);

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 Angular to make a request to a NodeJS+Express server for a simple GET operation

I need help with making a successful GET request from my Angular component to a NodeJS+Express server. someComponent.ts console.log("Before"); // send to server console.log(this.http.get('/email').map((res:Response) => { console.log(" ...

JQuery datepicker is functioning properly only after an alert when loaded with AJAX

Here's a puzzling question I have encountered. I implemented a field with a datepicker functionality. This field gets loaded into a div through an AJAX call. To sum it up, everything seems to be in working order.. But there's a strange issue. I ...

What is the process for integrating ion-tabs with IonicVueRouter within an Ionic (vue.js) application?

My Project Idea I have a vision to create an innovative exercise warm-up application. The app will be divided into two main sections: a workout tab and a settings tab. The user journey will start with selecting a workout plan, then choosing specific exerc ...

The scroll function is failing to activate at the desired location

I've been trying to fine-tune a window scroll function I created. Initially, I attempted to use waypoints for this, but unfortunately, I couldn't get it to work as expected. The main issue I'm facing is that the function triggers too early ...

Tips for implementing both an onChange and onSubmit event for a MUI TextField

I'm currently working with React and MUI and have created a form like the following: const handleUserInput = (event) => { set_user_input(event) } const handleSubmitForm = () => { if (user_input == 'help'){ ...

Utilizing web components in React by solely relying on a CDN for integration

I have a client who has provided us with a vast library of UI elements that they want incorporated into our project. These elements are stored in javascript and css files on a CDN, and unfortunately I do not have access to the source code. All I have at my ...

Techniques for incorporating a variable into the value field in JavaScript

let y = data[1]; cell1.innerHTML ='<input id="text" type="text" value= "'y'"/>' ; This snippet of code does not render any content when attempting to pass the variable, but if you provide a specific value like "h", it will displa ...

The MongoDB GridFS is refusing to accept the buffer being written

Hey everyone, I've been working on this issue for nearly a day now and can't seem to figure it out. I'm utilizing multer's inMemory flag to upload an image from my website. My approach involves writing the buffer received from multer to ...

Choose the currently active md-tab within the md-dialog's md-tab-group

I need to create a dynamic md-dialog with an md-tab-group that has two tabs. The md-dialog should open based on the button clicked, displaying the corresponding tab content. The initial template where the md-dialog is triggered: <button md-button class ...

Expandable Grid Sections in React MUI

Is there a way to create a grid layout where items with showDefault: true are always displayed at the top, and then users can click an arrow button to expand the grid and also show the items with showDefault: false? Any suggestions on how to achieve this? ...

The title of the homepage is showing up behind the AppBar. Any suggestions on how to correct this?

I encountered an issue with my appBar where the homepage was appearing behind it instead of below it. Here is a snapshot of the problem: https://i.stack.imgur.com/27LjB.png Below are the codes for the AppBar: const Header = () => { const [value, setV ...

How do you trigger the playback of a specific audio file when a user clicks on it?

I'm currently working on an interactive music app that mimics the functionality of a piano. Users are able to click on different boxes on the screen, triggering a unique musical note to play. While I initially considered manually collecting all the I ...

Instructions on implementing getJSON in this code

I recently set up a chained select box with JSON data to populate options, using this Fiddle. While the data is hardcoded for now, I am looking to load it using the $.getJSON() method. However, despite my efforts, I haven't been able to get the code r ...

Emphasize rows in the MUI-Datatables framework

A table was created using React.js and MUI-Datatables: import MUIDataTable from "mui-datatables"; const columns = ["Name", "Company", "City", "State"]; const data = [ ["Joe James", "Test Corp", "Yonkers", "NY"], ["John Walsh", "Test Corp", "Hartford", ...

The "add to cart" button is unresponsive

My issue is that the add to cart button on my website is not responding properly. I have implemented JavaScript on the add to cart button, where I have assigned an attribute called data-product with a value of {{product.id}}. var updateBtns = document.g ...

Unable to render properly after saving to Firebase

Currently, I am working on developing an express app that creates a Google map using geo coordinates extracted from photos. My goal is to utilize Firebase for storing data related to the images. While my code is functioning properly, I encountered an issue ...

Understanding the res.render method in JavaScript can be a bit tricky at first

In my spare time, I have been immersing myself in coding lessons and have encountered some puzzling aspects of the code: Firstly, there is a confusion surrounding the action attribute in HTML Secondly, this particular piece of code is causing me some b ...

Can you please provide a detailed list of all the events that are compatible with the updateOn feature in Angular's ngModelOptions?

The reference documentation notes the following: updateOn: a string that specifies which event should be bound to the input. Multiple events can be set using a space delimited list. There is also a special 'default' event that aligns with the ...

Angular - Implementing service worker to extract dynamic ID from route in "Notificationclick" event?

I have integrated push notifications into my code to notify users when an action is taken. The backend was developed using lib.net.webpush 3.1.0 with .net 4.5.2 in C#. The notification system is functioning well, but I am facing a challenge: Within my ser ...

JavaScript that Implements MVC Architecture Using C#

When working on a cshtml page within my View, I am able to easily retrieve the URL to an action using this line of code: <h1>@Url.Action("NewComment", "Case")</h1> If I include the same code in JavaScript like this: <script> alert( ...