jon
jon

Reputation: 1808

JS Declare and assign multi variable inLine es6?

it possible to declare and assign multi variable in same line with es6 syntax ? just example here, suppose i need to give value "50" to mX,mY,mXDZ,mYDZ. How i can perform this ?

let [mX,mY,mXDZ,mYDZ] = 50;
let mX,mY,mXDZ,mYDZ = 50; // !just why not! 

I am mainly looking for readability.

Upvotes: 1

Views: 3764

Answers (2)

Pointy
Pointy

Reputation: 413702

You can declare all the variables and then in a separate statement initialize them:

let mX,mY,mXDZ,mYDZ;
mX = mY = mXDZ = mYDZ = 50;

In a variable declaration statement (let, var, or const), the syntax is such that each individual variable can have an initialization expression. There are no provisions for multiple initializations from one expression.

With destructuring, you could do this:

let [mX, mY, mXDZ, mYDZ] = [50, 50, 50, 50];

but that doesn't seem "better" in any way to me, at least for readability. It seems error-prone.

It's very important to note that

let mX = mY = mXDZ = mYDZ = 50;

is definitely not correct. That statement is parsed as

let mX = (mY = mXDZ = mYDZ = 50);

That will create one local variable ("mX") and three implicit global variables. In "strict" mode it would be an error; in non-strict mode it's also an error but it's harder to debug.

Upvotes: 1

Bergi
Bergi

Reputation: 664287

No, that's not exactly possible. Destructuring needs a thing with multiple values1 to be assigned to multiple targets, not a single value. You can however cheat:

function* repeat(x) { while(true) yield x; }

let [mX, mY, mXDZ, mYDZ] = repeat(50);

Apart from that, in a multiple declaration every variable needs its own initialiser:

let mX = 50, mY = 50, mXDZ = 50, mYDZ = 50;

for which you can of course also use one shared variable:

let val = 50, mX = val, mY = val, mXDZ = val, mYDZ = val;

1: You can also destructure the same property multiple times (let {val:mX, val:mY, val:mXDZ, val:mYDZ} = {val:50};), but it still requires an object.

Upvotes: 6

Related Questions