Value of variable not getting updated after assignment - javascript

var a = 2;
var b = a;
console.log( b ); //2
a= 5;
console.log( b ); //2
Q: Why variable 'b' is getting value 2 even when variable 'a' is assigned a different value

console.log(b) returns 2 because when you access a primitive type you work directly on its value.

Cause numbers are immutable.
Changing an immutable value, replaces the original value with a new value, hence the original value is not changed (thats why b = 2).
If you need a reference, use object and/or arrays
var a ={value: 2}, b = a
a.value = 3 // also changes the value of be, since it can mutate

In javascript, primitives (number, bool, string) are assigned by value, only objects are assigned by reference.

In Javascript, integers are immutable. It means that the object's value once assigned cannot change. When you do
a=5;
b=a;
It is true that both are names of the same object whose value is 5.
Later when you do -
a=2
It assigns the reference a a new object whose value is 2. So essentially a now points to a new object. Ans both objects exist.
For a better understanding you can refer to this link

When doing Assignment of primitive values in javascript:
It's important to point out that this assignment does not tie a and b together. In fact all that happened was that the value from a was copied into b, so when we go to change a we don't have to worry about affecting b. This is because the two variables are backed by two distinct memory locations – with no crossover.
In brief way:
When you assign b = a
Actually you didn't copy the reference of a variable and make b point to the same variable location in memory.
You only copy the value of a variable and put it in new variable b with different memory location.

Related

Why manipulating a duplicated array reflects the origined array too [duplicate]

Consider this tiny bit of javascript code:
var a = [1, 2, 3],
b = a;
b[1] = 3;
a; // a === [1, 3, 3] wtf!?
Why does "a" change when I update "b[1]"? I've tested it in Firefox and Chrome. This doesn't happen to a simple number for example. Is this the expected behaviour?
var a = 1,
b = a;
b = 3;
a; // a === 1 phew!
It's the same array (since it's an object, it's the same reference), you need to create a copy to manipulate them separately using .slice() (which creates a new array with the elements at the first level copied over), like this:
var a = [1, 2, 3],
b = a.slice();
b[1] = 3;
a; // a === [1, 2, 3]
Because "a" and "b" reference the same array. There aren't two of them; assigning the value of "a" to "b" assigns the reference to the array, not a copy of the array.
When you assign numbers, you're dealing with primitive types. Even on a Number instance there's no method to update the value.
You can see the same "they're pointing to the same object" behavior with Date instances:
var d1 = new Date(), d2 = d1;
d1.setMonth(11); d1.setDate(25);
alert(d2.toString()); // alerts Christmas day
In addition to the other answers, if you want a copy of an array, one approach is to use the slice method:
var b = a.slice(0)
All Javascript objects are passed by reference - you would need to copy the entire object, not assign it.
For arrays this would be simple - just do something like:
var a = [1, 2, 3];
var b = a.slice(0);
where slice(0) returns the array from offset 0 to the end of the array.
This link has more info.
There is a difference between Value types and Reference types.
Basicly Value types are stored on the computers "Stack" directly which means that you actualy have the "Value" and not what is called a Pointer/Reference.
A Reference Type on the other hand, does not hold the actual value of the object/variable but instead it points ( references ) to where you can find the value.
Thus when you say "My Reference Type B points to what Reference Type A points to", you actually have two variables pointing in the same direction and when you interact with either of them and change something, both will be pointing to the changed place, since the pointed to the same place from the begining.
In your other case you say "Hey, copy the value in variable A to variable B" and thus you have the values on seperate places which means that any change to either of them will not affect the other.
Because arrays are references to actual place where they are stored.
the statement x = y is the only special one here, it means "point the variable x at the object y.
Pretty much every other operation is an operation which changes the object referred to by x
b = a;
b[1] = 3;
So, your first statement points the variable b at the array also referred to as a
Your second statement alters the array pointed to by b (and also by a)
Assigning an array does not create a new array, it's just a reference to the same array. Numbers and booleans are copied when assigned to a new variable.

value of duplicated array row changing original row [duplicate]

Consider this tiny bit of javascript code:
var a = [1, 2, 3],
b = a;
b[1] = 3;
a; // a === [1, 3, 3] wtf!?
Why does "a" change when I update "b[1]"? I've tested it in Firefox and Chrome. This doesn't happen to a simple number for example. Is this the expected behaviour?
var a = 1,
b = a;
b = 3;
a; // a === 1 phew!
It's the same array (since it's an object, it's the same reference), you need to create a copy to manipulate them separately using .slice() (which creates a new array with the elements at the first level copied over), like this:
var a = [1, 2, 3],
b = a.slice();
b[1] = 3;
a; // a === [1, 2, 3]
Because "a" and "b" reference the same array. There aren't two of them; assigning the value of "a" to "b" assigns the reference to the array, not a copy of the array.
When you assign numbers, you're dealing with primitive types. Even on a Number instance there's no method to update the value.
You can see the same "they're pointing to the same object" behavior with Date instances:
var d1 = new Date(), d2 = d1;
d1.setMonth(11); d1.setDate(25);
alert(d2.toString()); // alerts Christmas day
In addition to the other answers, if you want a copy of an array, one approach is to use the slice method:
var b = a.slice(0)
All Javascript objects are passed by reference - you would need to copy the entire object, not assign it.
For arrays this would be simple - just do something like:
var a = [1, 2, 3];
var b = a.slice(0);
where slice(0) returns the array from offset 0 to the end of the array.
This link has more info.
There is a difference between Value types and Reference types.
Basicly Value types are stored on the computers "Stack" directly which means that you actualy have the "Value" and not what is called a Pointer/Reference.
A Reference Type on the other hand, does not hold the actual value of the object/variable but instead it points ( references ) to where you can find the value.
Thus when you say "My Reference Type B points to what Reference Type A points to", you actually have two variables pointing in the same direction and when you interact with either of them and change something, both will be pointing to the changed place, since the pointed to the same place from the begining.
In your other case you say "Hey, copy the value in variable A to variable B" and thus you have the values on seperate places which means that any change to either of them will not affect the other.
Because arrays are references to actual place where they are stored.
the statement x = y is the only special one here, it means "point the variable x at the object y.
Pretty much every other operation is an operation which changes the object referred to by x
b = a;
b[1] = 3;
So, your first statement points the variable b at the array also referred to as a
Your second statement alters the array pointed to by b (and also by a)
Assigning an array does not create a new array, it's just a reference to the same array. Numbers and booleans are copied when assigned to a new variable.

Setting a variable equal to another variable [duplicate]

This question already has answers here:
Is JavaScript a pass-by-reference or pass-by-value language?
(33 answers)
Closed 2 years ago.
I have a few questions about setting a variable equal to another variable in JavaScript.
Let's say we create an object, a and set b = a.
var a = {
fname: "Jon",
lname: "Smith",
age: 50
}
var b = a;
I understand that if we change one of a's properties b will also be changed because when we set b = a we don't clone a's data, but rather create a reference to a's data. For example if we set a.fname = "Sarah", the new value of b.fname will be "Sarah".
If we try to "clear" a though by setting a = {}, object b will remain unchanged. I don't understand why manipulating an object in this way produces a different result than in the 1st example.
Also I have a question about the following scenario.
var x = 10;
var z = x;
If we then set x = 20, the value of z remains unchanged. Based on the behavior described in my 1st question, one would think that the new value of z would reflect the new value of x. Could someone please explain what I am missing here?
Thank You!
The really short answer to both your questions is that when you make one variable equal to another, a COPY of what's in the first variable is made and stored in the second variable - there is no linkage between the two variables.
But, read on for more details and why it can seem like there is a link in some cases...
JavaScript, like many languages, divides data into two broad categories: value types and reference types. JavaScript value types are its primitives:
string
number
boolean
null
undefined
symbol
When you assign any of these types to a variable, the actual data is stored in that variable and if you set one variable equal to another, a copy (not a linkage) of the primitive is made and stored in the new variable:
var a = 10; // Store the actual number 10 in the a variable
var b = a; // Store a COPY of the actual number stored in a (10) in the b variable
a = 50; // Change the actual data stored in a to 50 (no change to b here)
console.log("a is: " + a); // 50
console.log("b is: " + b); // 10
When you work with reference types, something a little different happens. Assigning a variable to a reference type means that the variable only holds a reference to the memory location where the object is actually stored, not the actual object itself. So, when you do this:
var a = {foo:"bar"};
a does not actually store the object itself, it only stores the memory location for where the object can be found (i.e. 0x3C41A).
But, as far as setting another variable equal to the first goes, it still works as it did with primitives - - a copy of what's in the first variable is made and given to the second variable.
Here's an example:
// An object is instantiated in memory and a is given the address of it (for example 0x3C41A)
var a = {};
// The contents of a (the memory location of an object) is COPIED into b.
// Now, both a and b hold the same memory location of the object (0x3C41A)
var b = a;
// Regardless of whether a or b is used, the same underlying object
// will be affected:
a.foo = "test";
console.log(b.foo); // "test"
// If one of the variables takes on a new value, it won't change
// what the other variable holds:
a = "something else";
console.log("a is: ", a); // The new string primitive stored in memory
console.log("b is: ", b); // The object stored in memory location (0x3C41A)
So, in your first tests, you've simply got two ways of accessing one object and then you change what a is holding (the memory location of the object) to a different object and therefore now you only have one way left to access the original object, through b.
If we try to "clear" a through by setting a = {}, object b will remain
unchanged. I don't understand why manipulating an object in this way
produces a different result than in the 1st example.
Because now we know that a = {} isn't clearing the object. It's just pointing a at something else.
In your first case:
var a = {
fname: "Jon",
lname: "Smith",
age: 50
}
var b = a;
a = {}
b remains unchanged because this is the sequence of events happening in the background:
You create an object at memory address 0x1234 with the data
fname: "Jon",
lname: "Smith",
age: 50
A pointer to that memory block is stored ina.
Then that pointer is copied to b
At this point there are two references to the same bit of memory. Altering anything in that memory block will affect both the references to it.
a = {} doesn't clear out memory block 0x1234, but creates a new object on another memory location (0x1235) and stores a pointer to that block in a. The memory at 0x1234 remains unchanged because b is still pointing to it.
There is a difference in this sort of memory management between simple variables and objects/pointers. Strings and numbers are of the simple variety and are 'passed by value' as opposed to being 'passed by reference' for objects.
Let me try to explain:
1) In your example a and b are references to one and the same object, while a.fname (or b.fname) is an attribute of that object. So when manipulating the attribute it will be changed in the object, while the references won't be affected, they still point to the same object, the object itself has been changed. a = {} on the other hand will just replace the reference to the object without affecting the object itself or b's reference to It. It's no clearance btw you only just created a new reference to a new empty object.
2) These are not objects, so there is no reference you are directly manipulating the values. That' s because there's a difference between objects and primitives which might get confusing especially in the beginning if you're not used to working with strict types.

Why number are immutable in Javascript?

I have read the question and answer here:
javascript numbers- immutable
But it's not enough clear for me why the number (primitive type) are immutable? Just because they create a new reference but not overwrite the value?
If on each assignemt is created a new reference
var x = 5;
x = 1;
Would we have 100 times a new reference in the following loop?
while (x < 101)
{
x++;
}
Is that efficient? I think I am not seeing correctly.
I'm honestly not quite sure what kind of answer you expect since I don't quite understand what you are confused about. But here we go:
Would we have 100 times a new reference in the following loop?
Variables are just containers for values. At a low level a variable is basically just a label for a memory address or a register. E.g. variable x might point to register R1.
x++ would simply increment the number that is stored in that register by 1. Lets assume our register looked like this:
R1: 5
After incrementing it, which can be a single operation, such as ADD R1 1, we would get
R1: 6
I.e. we simple overwrote the previous value with a new one. And we do that multiple times.
Is that efficient? I think I am not seeing correctly.
Incrementing a number by one is as simple of an operation as it can get.
Sure, you could implement mutable numbers on a higher level, but it certainly wouldn't make things more efficient or simpler.
Mutability doesn't make much sense for "single value" values, because mutating such a value basically means replacing it with a different value "in place".
Mutability makes more sense for values that are composed of other values such as lists and dictionaries, where one part changes and the other stays the same.
Additionally, mutability only seems relevant when a language has reference type data types. With that I mean that multiple variables can hold a reference to the very same value of a data type. Objects are reference-type in JavaScript, which allows you to do this:
var a = {foo: 42};
var b = a;
b.foo = 21;
console.log(a);
If data types are not of a reference-type, called value-type, (which primitive values are in JavaScript), then mutability doesn't matter because it would be indistinguishable from immutability. Consider the following hypothetical scenario with a mutable, value-type number:
var a = MutableNumber(42);
var b = a; // creates a copy of MutableNumber(42) because it's a value type
a.add(1);
console.log(a, b); // would log 43, 42
In this scenario it is not possible for two variables to refer to the same mutable number value, a.add(1) is indistinguishable from assigning a new value to a (i.e. a = a + 1).
I could understand your question , the thing is , inside the while loop , everytime the x will point to the new value , whereas the old value will be made ready for garbage collection , so the memory is mantained still.
Read this for better understanding :
https://developer.mozilla.org/en-US/docs/Glossary/Mutable
So about the mutablity , your understanding is correct , the variable references the new value , the old value isn't changed , hence primitive values are immutable.
Refer: https://developer.mozilla.org/en-US/docs/Glossary/Primitive
Mutation is a change of state while numbers (the primitive type) are pure state objects. Any mutation to such a "object" state is actually a new number. Number itself is like an identifier of a mutation of bits in a cell of computer memory.
Therefore numbers are not mutable. Same as colors or characters.
It is also worth claryfining that a new number will ocupy the same memory cell as the old one for any given variable. Actually replacing the old one. Therefore there is no performance hit of any kind.
i dont understand entirely this,
var a=12;
a=45;
we can infer from ;
1.firstly interpreter allocate a chunk of memory and locate 12 to this area.
actually (a) is label of this memory area.
2.than, interpreter allocate a new memory cell and locate 45 to this area.
lastly (a) is associated with this new memory cell. The memory cell that contain 12 is destroyed by garbage collector.
Primitive values vs. references:
In JavaScript values of type boolean, undefined, null, number, symbol, string are primitive. When you assign them to a variable or pass them as an argument to a function, they always get copied.
In contrast objects have two parts to them: Object (it's data) is stored in one chunk of memory and what you assign to a variable is a reference pointing to that object. Object itself is not copied on assignment.
Because numbers are always copied when you assign them to a variable it is impossible to change a number and see that change through some other variable without actually assigning a new value to that variable.
In contrast when you change a field on an object, all variables pointing to that object will see that change.
Let's see some examples:
var a = 1;
var b = a; //This creates a new copy of value 1
console.log(a, b); // 1 1
a = 2;
console.log(a, b); // 2 1
var obj_a = {attr: 1};
var obj_b = obj_a; //This makes a new reference to the same object.
console.log(obj_a, obj_b); // {'attr': 1} {'attr': 1}
obj_b.attr = 2;
console.log(obj_a, obj_b); // {'attr': 2} {'attr': 2}
Immutable objects: immutable.js
Libraries like immutable.js provide types that combine properties of primitive types and objects: Types from immutable.js behave as ordinary objects as long as you don't change them. When you change a property of an immutable object, a new object is created and the change is only visible through that new object. The benefit is that you save space in memory and you can quickly check equality of objects by just comparing their references. You get a set of types that behave like integers but you can store more complex structures in them.

Why does changing one array alters the other?

Consider this tiny bit of javascript code:
var a = [1, 2, 3],
b = a;
b[1] = 3;
a; // a === [1, 3, 3] wtf!?
Why does "a" change when I update "b[1]"? I've tested it in Firefox and Chrome. This doesn't happen to a simple number for example. Is this the expected behaviour?
var a = 1,
b = a;
b = 3;
a; // a === 1 phew!
It's the same array (since it's an object, it's the same reference), you need to create a copy to manipulate them separately using .slice() (which creates a new array with the elements at the first level copied over), like this:
var a = [1, 2, 3],
b = a.slice();
b[1] = 3;
a; // a === [1, 2, 3]
Because "a" and "b" reference the same array. There aren't two of them; assigning the value of "a" to "b" assigns the reference to the array, not a copy of the array.
When you assign numbers, you're dealing with primitive types. Even on a Number instance there's no method to update the value.
You can see the same "they're pointing to the same object" behavior with Date instances:
var d1 = new Date(), d2 = d1;
d1.setMonth(11); d1.setDate(25);
alert(d2.toString()); // alerts Christmas day
In addition to the other answers, if you want a copy of an array, one approach is to use the slice method:
var b = a.slice(0)
All Javascript objects are passed by reference - you would need to copy the entire object, not assign it.
For arrays this would be simple - just do something like:
var a = [1, 2, 3];
var b = a.slice(0);
where slice(0) returns the array from offset 0 to the end of the array.
This link has more info.
There is a difference between Value types and Reference types.
Basicly Value types are stored on the computers "Stack" directly which means that you actualy have the "Value" and not what is called a Pointer/Reference.
A Reference Type on the other hand, does not hold the actual value of the object/variable but instead it points ( references ) to where you can find the value.
Thus when you say "My Reference Type B points to what Reference Type A points to", you actually have two variables pointing in the same direction and when you interact with either of them and change something, both will be pointing to the changed place, since the pointed to the same place from the begining.
In your other case you say "Hey, copy the value in variable A to variable B" and thus you have the values on seperate places which means that any change to either of them will not affect the other.
Because arrays are references to actual place where they are stored.
the statement x = y is the only special one here, it means "point the variable x at the object y.
Pretty much every other operation is an operation which changes the object referred to by x
b = a;
b[1] = 3;
So, your first statement points the variable b at the array also referred to as a
Your second statement alters the array pointed to by b (and also by a)
Assigning an array does not create a new array, it's just a reference to the same array. Numbers and booleans are copied when assigned to a new variable.

Categories

Resources