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.
Related
I want to know for what reason the programme is working in the second case but not in the first one.
CASE1:-
let tem=document.getElementById('timed').value
let timeBtn=document.getElementById('timed_input');
timeBtn.addEventListener('click',()=>{
console.log(tem);
})
CASE2:-
let timeBtn=document.getElementById('timed_input');
timeBtn.addEventListener('click',()=>{
console.log(document.getElementById('timed').value);
})
Because value is very likely to be a primitive data type. When you assign a primitive value to a variable, the value is copied to the variable. In contrast, when you assign an object to a variable, you get a reference of the object and not a copy of it.
Take a look at this example.
let a = 20;
let b = a;
a = 30;
console.log(a); // 30
console.log(b); // 20
Even though we assign let b = a, we stored the value of a (20) into b, b and a don't have a relation to each other.
In contrast with non primitive data types, like objects:
let a = { name: "Doria", age: 22 };
let b = a;
b.name = "Nicole";
console.log(a.name); // Nicole
console.log(b.name); // Nicole
In this case, a and b are related, in the sense that they are referencing the same object.
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.
In javascript arrays are objects therefore passed by reference. So
var a = ["a"];
var b = a;
console.log(b);
a[0] = "wtv";
console.log(b);
will change b value.
what I don't understand is why
var a = ["a"];
var b = a;
console.log(b);
a = ["wtv"];
console.log(b);
is not changing b value ? what is the reasoning behind this ?
Because the value in memory a points to is changed by the assignment a = ["wtv"];.
while in the first example you change a part/property of a, while the object in memory a points to stays the same.
An image to explain it:
It's because you're b is just copying a reference to a.
So they have copies of the same reference, but they each have their own copy of that reference.
var a = ["a"];
// b now holds a copy of the reference from a
var b = a;
// when you change a, b is unaffected since it has an independent reference
// a now points to a new location in memory
// a has a new reference, whereas b still has the reference from before
a = ["wtv"];
However, since the two variable do have the same reference, even though they are copies, you can change data within the object or array itself and have it affect both variables.
Take this for example:
// a points to a location in memory
var a = [];
// we give a some value
a["foo"] = 'bar';
// b now has a *copy* of a's location in memory
var b = a;
// since b shares the same location in memory as a, it has the same foo value
console.log(b.foo); // => bar
// we update a's foo value
a["foo"] = 'baz';
// since b still shares the same location in memory as a,
// it's pointing to the same foo from a, therefore it's also affected
console.log(b.foo); // => baz
#Hidde has a great image that helps visualize what's going on behind the scenes with where the memory is pointing.
With a = ["wtv"]; you assign brand new array to variable a. It has nothing to do with it's former reference.
An array in JavaScript is also an object and objects are always passed/assigned by reference. Thus both variables have a reference to the same object, thus making a change in one will reflect a change in another as both are pointing to the same value.
Whereas in the later case, you are assigning a new value to the var a and this will be stored at different memory location and not on the one on which b is stored, it is similar like doing
var a = 5;
var b = a;
a = a - 1;
alert(b); // alerts 5
alert(a); // alerts 4
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)
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;