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

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.”

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)