How / why to do variable chaining with operator = (equality)?

8

Sometimes I come across these statements threaded in source some libraries and there are usually many chained statements. For example:

var foo = foo2 = foo3 = 'foovalue';

However I have never been able to understand the meaning of this, much less a practical use.

I once found it convenient to make a shortcut to a statement:

var e = window.counter = 0;

That's just not to repeat window.counter in my conditionals. It even worked only that in the course of the script, using this shortcut did not update the value of window.counter .

In the end, I'm seeking a light on this practice.

    
asked by anonymous 28.02.2015 / 23:11

1 answer

6

This operator is used to assign more than one variable at the same time, neither more nor less. It's hard to think of such a practical use in the abstract, but I would say that if you need to initialize multiple variables of the same value into a complex algorithm, each of these variables will evolve independently, this would be an appropriate use:

var inicio = fim = atual = 10;
while ( ... ) {
    if ( lista[inicio-1] <= lista[atual] )
        inicio--;
    if ( lista[fim+1] >= lista[atual] )
        fim++;
}
// o intervalo [inicio,fim] está ordenado (em relação ao atual)

Another possibility is when you want to update more than one data structure with the same value (it may be necessary if two or more different libraries are acting on the same object):

x.atual = y.selecionado = z.emFoco = { ... };

Etc. The key point here is that they are independent variables, which may in other circumstances have values different from each other, but at a given time it is desirable that all have the same value. If a single value is required, it is preferable to use a variable only (delegating access to it through accessor functions, if necessary).

// Leitura
function e() { return window.counter; }

// Ou leitura-escrita
function e(v) { return v !== undefined ? window.counter = v : window.counter; }

// Uso
var x = e();
e(10);

P.S. The semantics of the chained operator - if this is not clear - is to assign the all variables to the left of the last = the value to the right of it.     

28.02.2015 / 23:23