Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to do multiple assignment and initialization with block scope?

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!

like image 547
Roger Heathcote Avatar asked Jan 09 '17 15:01

Roger Heathcote


People also ask

Can you do multiple assignments in Java?

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.

Is multiple assignment possible in C?

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.

How do you write multiple assignments in Python?

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.


2 Answers

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.

like image 188
James Thorpe Avatar answered Sep 19 '22 04:09

James Thorpe


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
like image 34
Oriol Avatar answered Sep 22 '22 04:09

Oriol