Javascript "Equal Sequence" means

Sometimes on the Internet I see syntax that is unfamiliar to me. Sort of:

console.log = console.error = console.info = console.debug = console.warn = console.trace = function() {} 

How does this "equal" sequence work?

Thanks.

+6
source share
3 answers

The assignment operator assigns a value to its left operand based on the value of its right operand.

Consider:

 a = b = c = d = 5; 

The expression is allowed from right to left like this:

d = 5 and c = d (which equals 5), b = c (5), etc.

In your example, these console methods all (re) are defined as an empty function.


See: MDN: Assignment Operators for more information.

+5
source

When assigning operations are allowed from right to left. Thus, the rightmost value will be populated in all previous variables.

+5
source

What you describe can be easily explained by analogy using a simpler example:

 // Normal variable assignment var a, b; a = 15; b = 15; console.log("a: "+a+" , b: "+b); // Assing the same value to two variables var c, d; c = d = 15; console.log("c: "+c+" , d: "+d); // Assign the same value to two variables and make it a function var e, f; e = f = function(){ console.log("Hi!"); }; // Call both of the variables' functions e(); f(); 

Starting with variables a and b , you go to c and d , which are assigned the same value. The conclusion here is that you can assign one value to two variables, and the expression will be evaluated from right to left, so, in fact, it equally assigns the values ​​of two variables separately. However, this does not mean that transcoding one will also change the other. Finally, see what happens to e and f . They are assigned a function instead of a value, so you can call them as if they were functions.

Short version : expression resolves from right to left. Assignment is carried out by value, not by reference, which means that changing one of the variable values ​​will not affect the others. Finally, if you assign a function to your variables, you can use their names to call the function, which is their value.

+1
source

Source: https://habr.com/ru/post/1012661/


All Articles