javascriptvariablesmultinomial

usage of multinomial assign javascript?


It is possible to assign multinomial variable in javascript like

let a = 10;
let b = a = 2; // like this
console.log(`a - ${a}, b - ${b}`); // prints "a - 2, b -2"

However, I could not find which case this expression is useful. Is there any good reference of this usage? (If this expression does not have particular strengths, should I block this in lint?)


Solution

  • There's nothing special about this, that's why you can't find any reference for it.

    When you write

    let b = a = 2;
    

    it's just an instance of the general syntax

    let <variable> = <expression>;
    

    The expression happens to be a = 2 -- an assignment is an expression that has the side effect of setting the variable and returns the value that was assigned. It's effectively the same as

    a = 2;
    let b = a;
    

    Notice that there's no declaration there for a. If you hadn't declared a on the previous line, it would be assigned as a global variable rather than being a local variable declared with let (assuming this code is inside a function). Only b is being declared.