I searched through the internets but could not find a relevant search criteria so I thought this would be the best place to ask.
I have a JS statement saying
document.location.hash = this.slug = this.sliceHashFromHref(href)
How does this work??
I searched through the internets but could not find a relevant search criteria so I thought this would be the best place to ask.
I have a JS statement saying
document.location.hash = this.slug = this.sliceHashFromHref(href)
How does this work??
How does this work??
a = b
can be seen as both a statement and an expression.
The result of the expression is b
.
In other words,
a = b = c;
which can be written as
a = (b = c);
is equivalent to
b = c;
a = b;
Thus your code is equivalent to:
this.slug = this.sliceHashFromHref(href);
document.location.hash = this.slug;
Be aware of the variables scope!!
var A = B = C = 3; //A is local variable while B & C are global variables;
var A = 3 , B = 3, C = 3;// A B C are local variables;
It gets evaluted from right to left. i.e.
document.location.hash = this.slug = this.sliceHashFromHref(href)
means the output/value of this.sliceHashFromHref(href)
is assigned to this.slug
and then to document.location.hash
.
Quite easy... It assigns the result from the call to this.sliceHashFromHref(href)
to both document.location.hash
and this.slug
, so both properties (variables) contain the same value after the line has been executed.
In Javascript (and several other languages that derive their syntax from C) an assignment evaluates the item to the right of the = symbol and assigns it to the variable on the left. The item on the right can itself be an assignment with an = operator. What happens is the rightmost expression is evaluated, the value assigned to the middle variable, and then that value is assigned to the variable on the left.
In short, it's simply a way to assign a value to multiple variables at once.
Actually Ma Jerez's answer makes a very important point here. also this answer refers to this similar question: this question involves a few things:
=
assignment order: it goes from right to left;example1:
;(function Anonymous(){
var a = b = {};
console.log(a==b); //true
})();
a
was hoisted in the Anonymous
execution scope.
b
is going to be assigned as {}
, but because b
is not defined, b
is assigned to the global context window
, then window.b
is assigned {}
; then window.b = {}
return
s {}
.
local variable a
is assigned as {}.
Therefore, a few interesting things happen here: the local variable a
and the global variable b
both point to the same object {}
, so they are ==
and ===
; remember that {}=={}
gives false
otherwise.
Note: if in strict mode:
;(function Anonymous(){
'use strict'
var a = b = {}; //Uncaught ReferenceError: b is not defined
})();
this consecutive assignment won't work the same way...