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

Issue with Firefox not recognizing keydown events for the backspace key

I am currently developing a terminal emulator and have encountered an issue with capturing the backspace key in Firefox. While I am able to capture the first backspace press and delete the last character in the input prompt, the problem arises when trying ...

The image placeholder is missing

This is my custom Results component: This is my custom Thumbnail component: `import React from "react"; const Thumbnail = ({ result }) => { return ( <div> <h1>Thumbnail</h1> </div> ); }; export default Thumb ...

When transitioning between views in Angular App, it freezes due to the large data response from an HTTP request

I am encountering an issue with my Angular 9.1.11 application where it freezes after navigating from one page to another (which belongs to a different module with lazy loading). Here is the scenario: There is an action button called View Report that re ...

Tips for resolving an issue with an array and the find method?

Seeking guidance on using the find method. Specifically, I am tasked with searching an array to find a specific string match. The catch is that this string may be nested within one of the objects in its child array. I attempted to create an if statement in ...

Create a custom Angular directive that allows you to replace tags while inserting the template

I have created a custom directive that can take templates based on the attribute provided. Check out the Plnkr example JS var app = angular.module('app', []); app.directive('sample', function($compile){ var template1 = '<d ...

Guide on sending JSON messages between Node.js services within a Docker Compose environment

If I have two Node.js services running in a Docker Compose, one listening on port 4000 and the other on port 5000, how can I exchange JSON messages between them using Express? ...

How can you direct a user to a specific page only when certain conditions are met?

Currently using React in my single page application. I have a good grasp on how Routes function and how to create a PrivateRoute. The issue arises when I need to verify the user's identity before granting access to a PrivateRoute. My attempt at imple ...

The process of implementing server-side rendering for React Next applications with Material-ui using CSS

I have developed a basic React application using Next.js with an integrated express server: app.prepare() .then(() => { const server = express() server.get('/job/:id', (req, res) => { const actualPage = '/job' const ...

Exploring the process of breaking down a substantial string object into manageable key/value pairs using AngularJS

I gathered information from a text file called sample_resume.txt Name: John Doe Phone: (555) 555-5555 Email: [email protected] TARGET To succeed in the field of web development. SKILL SET Development: HTML5, JavaScript, Bootstrap, AngularJS, Rea ...

Create interactive highcharts graphs using data from a CSV file generated through PHP

I'm having trouble working with Highcharts and csv data. Take a look at this example: http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/line-ajax/ $.getJSON('http://www.highcharts.com/ ...

Utilizing Greek symbols within C++ programming language

Back in the day, I included Greek symbols such as α and ε in my variable declarations in C++ code with no issues. However, after switching to Ubuntu as my platform, I began encountering errors during compilation: stray ‘\316’ in progra stray †...

Struggling to make Tumblr Javascript function properly

I have integrated the following code snippet: <script type="text/javascript" src="http://underlineent.tumblr.com/api/read/json"> </script> Unfortunately, my Tumblr blog is not appearing on this site. Can anyone provide assistance? The provid ...

Utilizing AngularJS to Extract JSON Data from Gzipped Files Stored Locally via Ajax

Currently, I am attempting to retrieve and read a JSON file that is stored in data.gz using AngularJS's $http service. However, when I make the request, all I get back are strange symbols and characters as the response. My application is being run loc ...

Navigating JSON data with unexpected fields in Typescript and React.js

Looking to parse a JSON string with random fields in Typescript, without prior knowledge of the field types. I want to convert the JSON string into an object with default field types, such as strings. The current parsing method is: let values = JSON.parse ...

Getting to the values within a JSON object that contains multiple arrays

Is there a way to retrieve array data from the json object data? const [data, setData] = useState([]) const getData = () => { axiosInstance .get(url + slug) .then(result => setData(result.data)) } useEffect(() = ...

Tips for ensuring Node.js waits for a response from a substantial request

When uploading a large number of files, the process can take several minutes. I am currently using a multi-part form to post the files and then waiting for a response from the POST request. However, I am facing issues with timeouts and re-posting of files ...

Getting the Tweets of a Twitter-validated user using node.js

I'm struggling with extracting Tweets from a verified user and could use some assistance. I know it's a broad question, but here's the situation: https://github.com/ttezel/twit provides a way to access tweets from any Twitter account. Howev ...

Iterating over an array while postponing a function

My goal is to create a continuous loop through an array of number values. These values will be used as delay parameters in a setInterval function, triggering another function each time. Here's what I've come up with: HTML: <p>On</p> ...

What is the method for incorporating an async middleware into a router route?

I am currently setting up routes for an express router in my project. I have a validator that deals with promises, requiring me to use await in the code. Here is how it looks: constructor() { this.router = express.Router(); this.router.use(express. ...

The .forEach() method in Javascript is not suitable for DOM nodes as they are subject to change during the iteration

Having an issue with moving all DOM elements from one node to another, I initially used this code: div.childNodes.forEach((n) => me.container.appendChild(n)); However, I noticed that only half of the nodes were being copied. It seems that the problem ...