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.
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.
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.
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.
It only works if the var y
as been previously defined, otherwise y
will be global.
In such case, you better do:
var x, y; x = y = 'value';
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.”
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