Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is setting multiple variables in 1 line valid in javascript? (var x=y='value';)

This is valid in php:

$x=$y='value'; 

This will in esscence set both $x and $y to 'value'.

Is this valid in javascript?

var x=y='value'; 

I have tested it in chrome console and it worked as expected, but just wanted to double check before starting to use it.

like image 364
anonymous-one Avatar asked Sep 28 '11 09:09

anonymous-one


People also ask

Can you define multiple variables in one line JavaScript?

To define multiple variables on a single line with JavaScript, we can use the array destructuring syntax. const [a, b, c, d] = [0, 1, 2, 3]; to assign a to 0, b to 1 , c to 2, and d` to 3 with the array destructuring syntax.

How do you use multiple variables in JavaScript?

Declare Multiple Variables in JavaScript Copy var cost = 25; const name = "Onion"; let currency = "NPR"; However, there are shorter ways to declare multiple variables in JavaScript. First, you can only use one variable keyword ( var , let , or const ) and declare variable names and values separated by commas.

Can a variable have multiple values JavaScript?

There is no way to assign multiple distinct values to a single variable. An alternative is to have variable be an Array , and you can check to see if enteredval is in the array. To modify arrays after you have instantiated them, take a look at push , pop , shift , and unshift for adding/removing values.


1 Answers

It only works if the var y as been previously defined, otherwise ywill be global.

In such case, you better do:

var x, y; x = y = 'value'; 

Assignments Chaining

Another antipattern that creates implied globals is to chain assignments as part of a var declaration. In the following snippet, a is local but b becomes global, which is probably not what you meant to do:

// antipattern, do not use function foo() {    var a = b = 0;    // ... } 

If you’re wondering why that happens, it’s because of the right-to-left evaluation. First, the expression b = 0 is evaluated and in this case b is not declared. The return value of this expression is 0, and it’s assigned to the new local variable declared with var a. In other words, it’s as if you’ve typed:

var a = (b = 0); 

If you’ve already declared the variables, chaining assignments is fine and doesn’t create unexpected globals. Example:

function foo() {    var a, b;    // ...    a = b = 0; // both local } 

“JavaScript Patterns, by Stoyan Stefanov (O’Reilly). Copyright 2010 Yahoo!, Inc., 9780596806750.”

like image 159
user278064 Avatar answered Sep 22 '22 04:09

user278064