Javascript multiple assignment clarification? - javascript

Looking at var a=b=1; , I already know that both a and b has the same value.
But my question is :
Does the a gets its value from 1 or from b ?
I made a small test :
/*1*/ (function (){
/*2*/ var j = window.j = function (){ alert('3');};
/*3*/ window.j2 = j;
/*4*/ })();
/*5*/
/*6*/ window.j(); //3
/*7*/ window.j=null;
/*8*/ window.j2();//3
As you can see line #8 yields 3 so I persume that a is not having the value of b but the value of 1.
Am I right ?
visualize :
(function (){
var j = window.j = function (){ alert('3');};
|
| ^ ^
| | | //which one ?
+----------+--------+
})();

Assignment in javascript works from right to left. So you are getting your value from window.j. Re-setting window.j will not affect the result because Javascript variables always passes by value, exception is array or object.
Example of passing value by ref in JS object:
var obj = { x: 2 };
var anotherObj = obj;
anotherObj.x++;
alert(obj.x); //3
You can find more information here.
More useful examples available in this answer.

The "=" operator associates to the right so "a=b=1" is equivalent to "a=(b=1)". So 1 is assigned to b first with a result of 1, which is then assigned to a.

Assigment in JavaScript is right associative, so you are correct.
In
a = b = c;
a takes the value of b at time of assignment, so if b is later assigned to something else, a retains its value (which happens to be the same as c)

You are right technically but are confused with reference / value assignment i think. Technically a does get it's value from b but there is no reference to b therefore if your were to do b = null it would have no affect to a, which is what you're seeing in your example.
a inherits the value of b without relying on b still existing or having that same value later on when you refer back to a. The assignment happens right to left so actually reads a = ( b = 1)

Related

Why is the value of b printed as 23 and not 46?

My code:
var a = 23;
var b = a;
a = 46;
console.log(a);
console.log(b);
Why is the value of b printed as 23 and not as 46?
Output :
a=46, b=23,
In Javascript, Only Objects/Arrays are passed by reference and others are passed by value. As a and b hold integer values they are passed by value.
When var b = a; is executed, b does not "refer" to a. It becomes a number whose value is a's value at this moment.
However, if you use an Object, the attribution will use the reference of a, and not its value:
a = { value: 23 };
b = a;
a.value = 46;
console.log(b);
// console
Object { value: 46 }
Look at this answer. Primitives are passed by values and objects are passed by reference. As a and b are primitives, they are passed by values. And when a is changed that will not be reflected in b.
Because you are giving a value of a, and that is 23. Then you are reassign a to be 46.
in your code first you initialize a with value of 23 and then you assign value of a to b
var a = 23;
var b = a;
a = 46;
console.log(a);
console.log(b);
then you update value of a but not assigning it to b
As in Java-Script Only Objects/Arrays are passed by reference and others are passed by value. As a and b hold integer values they are passed by value.
so updating value of a did not result in change of b value ; if you assign value to b after updating value of a it would result in displaying value of 46 for both a and b
assignment operator means you assign the value of right side to the value of left side so by this statement var b = a; b becomes 23 and once you change a it has no affect on value of b due to lexical scoping of js.

understanding functions and numbers

var a = 3;
var b = 5;
example(a, b);
function example(b, a) {
var result = b - a;
alert(result);
}
My question is looking at this I though the result would be 2 but its negative 2 can someone explain why please?
You've inverted the arguments in your function definition.
While you are calling (a,b), you are receiving (b,a). This means that you are passing:
example(3,5)
and receiving:
(b=3, a=5)
You then return:
(b-a) or (3-5)
which is -2.
The actual names of the parameters in the function don't matter. You're getting confused because wherever you found the example- they cleverly reversed the order of b and a. However the names in the parameter are just used in the function scope and don't affect variables of the same name outside of it. For example:
var a = 3;
var b = 5;
example(a, b);
function example(bacon, eggs) {
var result = bacon - eggs;
alert(result);
}
Would also return -2 because the first parameter we pass through to example is a (3) and the second is b (5) and 3-5 = -2. Doesn't matter what the name of the parameters in example actually are named- its important to keep this in mind.
There is no problem with your code. The problem is with your lecture of the code. The result is in fact, -2. Debug your code in Chrome Debugger or similar
var a = 3; // a equals 3
var b = 5; // b equals 5
example(a, b); // Replacing variables this is the same as example(3,5)
// Changing variables names so you don't get mixed up
function example(c, d) {
// Since you called example(3,5) then c = 3 and d = 5
var result = c - d; // This results in -2
alert(result);
}
Don't be confused with the variable names because in js, it works by the order of your function argument not by variable name of functions. To get what you want as output i.e 2, try like this.
example(b = 5, a = 3);
function example(b, a) {
var result = b - a;
alert(result);
}
If you've any confusion go to http://www.pythontutor.com/javascript.html and see what is happening under the hood.

Cannot set backgroundColor when assigned to a variable

Trying to set a background color to the body of the document, I am puzzled as for why the following code does not work (tested in Chrome):
var a = 'blue';
var b = document.getElementById('body').style.backgroundColor;
b = a; // Not working.
while this works fine:
var a = 'blue';
var b = document.getElementById('body').style;
b.backgroundColor = a; // works.
and this works too:
document.getElementById('body').style.backgroundColor = 'blue'; //works
Can someone explain why the first version does not work?
This is a classic pointer user error. I've made this mistake many many times.
var a = 'blue';
var b = document.getElementById('body').style.backgroundColor;
b = a; // Not working.
The above code doesn't work because the value of document.getElementById('body').style.backgroundColor is being copied to the identifier b. When you reassign b with the value of a you're not re-assigning the value of document.getElementById('body').style.backgroundColor.
That why thiis code works:
var a = 'blue';
var b = document.getElementById('body').style;
b.backgroundColor = a; // works.
because you're saving the value of style to the identifier b. b a complex type. Now when you reassign b.style you're also re-assigning document.getElementById('body').style because the identifier b holds the same reference as document.getElementById('body').style.
Let me try to break that down:
In javascript (and many other languages) when you assign a complex type (i.e. an object or an array) to an identifier, you're actually assigning a reference to "something" in memory. You can think of the identifier's value being an "address" instead of holding all the values of the complex type, and when you try to pull values out of the identifier using the obj.prop syntax, you're actually telling the program to go to the address and fetch the desired value.
Therefore, if any property in that "something" changes, the references (aka pointers) will also reflect that change:
const complexType = {
a: 'something'
}
const x = complexType;
const y = complexType;
console.log(`from x: ${x.a}`);
console.log(`from y: ${y.a}`);
complexType.a = 'something else';
// notice how they change
console.log(`from x again: ${x.a}`);
console.log(`from y again: ${y.a}`);
To contrast, simple/primitive types are always copied on assignment. This means that the identifier hold the full value instead of holding an address. That means whenever you assign an identifier to a simple/primitive value, that value will persist even when you change the original value.
// original value
let simpleType = 'something';
let a = simpleType;
let b = simpleType;
console.log(`from a: ${a}`);
console.log(`from b: ${b}`);
// re-assign
simpleType = 'something else';
// notice how they *don't* change
console.log(`from a again: ${a}`);
console.log(`from b again: ${b}`);
So to conclude, document.getElementById('body').style.backgroundColor returns a simple type. This simple type get copied on assignment. That's why you can't do this:
var a = 'blue';
var b = document.getElementById('body').style.backgroundColor;
b = a; // Not working.
Hope that helps!
var b = document.getElementById('body').style.backgroundColor;
Acts like a getter and returns the background color of the element with the ID of body. It doesn't hold a pointer to it the way you seem to be thinking. So b would contain a string like purple or whatever color you set.
Then you're doing b = a; which will just overwrite the value of b with a's value.

Javascript "Equal Sequence" meaning

Sometimes in the internet I see a syntax that is strange to me. Something like:
console.log = console.error = console.info = console.debug = console.warn = console.trace = function() {}
How does this "equal" sequence work?
Thanks.
An 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 resolved right to left so:
d = 5 and c = d (which is 5), b = c (5) and so on.
In your example those console methods are all being (re)defined as an empty function.
See: MDN: Assignment Operators for more info.
With assignments, the operations are resolved from right to left. So the right most value will be populated into all the preceding variables.
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 from variables a and b, you then go to c and d that are given the same value. The takeaway here is that you can assign the same value to two variables and the expression will be evaluated from right to left, so in effect it's like assigning the two variables' values separately. However, this does not mean that chaning one will change the other as well.
Finally, see what happens with e and f. These are assigned a function instead of a value, so you can then call them as if they were functions.
Short version: Expression gets resolved from right to left. The assignment is by value, not by reference, meaning that changing one of the variables' value will not affect the others. Finally, if you assign a function to your variables, you can then use their names to call the function that is their value.

Something = Something = Something... What?

I'm reading some code and I see a comparison that's laid out like this:
a = b = c
Seeing as how searching Javascript about equal or comparison yields remedial results, anyone care to explain what's going on?
EDIT: These are all objects or object properties that we're talking about here, should have specified.
DOUBLE EDIT: This is inside of an Object.defineProperties() block.
= is an operator. It takes two arguments: a variable reference and an expression. It assigns the value of the expression to the variable, and returns the assigned value.
As a result, you can chain them and it equates to this:
a = (b = c)
In other words, assign b to the value of c, then assign that value to a also.
a = b = c is just shorthand expression for:
b = c;
a = b;
if(a = b) will always return true because it is assigning, instead of comparing. To compare, the statement should read: if(a == b).
The = operator associates right-to-left and evaluates to the value that was assigned.
So this:
a = b = c;
Means this*:
b = c;
a = c;
* Unless you're dealing with properties.
That is not a comparison. It is an assignment of the value of c to the b and a variables.
Assignment works right to left, so it is an assignment of c to b first. Then the return value of that operation is assigned to a.
The return value of an assignment operation is the value that was assigned, so a will get the same value assigned to b.
It equates this;
b = c; a = b;

Categories