I would like to declare two variables with block scope and initialize them to the same value. It would be nice if the following worked that way but it doesn't...
{
let a = b = "wang";
}
console.log("b:", b);
Variable 'a' has block scope but variable 'b' doesn't, it has function scope as if it were declared with a var.
Is there a one line* way of accomplishing this or do I have to do...
let a, b;
a = b = "wang";
* not that I would throw readability under a bus to save a couple of chars you understand, I'm just curious!
Java permits the use of multiple assignments in one statement. In such statements, the assignment operators are applied from right to left, rather than from left to right.
MultipleAssignment is a language property of being able to assign one value to more than one variables. It usually looks like the following: a = b = c = d = 0 // assigns all variables to 0.
Python assigns values from right to left. When assigning multiple variables in a single line, different variable names are provided to the left of the assignment operator separated by a comma. The same goes for their respective values except they should be to the right of the assignment operator.
You can do it in a single let
declaration as follows:
{
let a = "wang", b = a;
}
console.log("b:", b); //undefined or ReferenceError
Because both a
and b
are declared with let
inside the braces, they both get block scope. You have to assign a
first so that it's been assigned before you assign it to b
also.
You can use array destructuring with fill
to avoid repeating the value:
{
let [a, b, c, d] = Array(4).fill("wang");
console.log(a, b, c, d); // "wang", "wang", "wang", "wang"
}
a; // ReferenceError
If you don't want to bother about the number of variables and don't want to allocate big arrays, you can also use an immediately invoked generator function expression. For simplicity, it may be a good idea to implement this as a helper function
const repeat = function*(value){while(true) yield value};
{
let [a, b, c, d] = repeat("wang");
console.log(a, b, c, d); // "wang", "wang", "wang", "wang"
}
a; // ReferenceError
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With