Is variable updated "by reference"? - javascript

I have the following simple script.
<script>
SPC = {
a : [10],
b : 10,
t: function()
{
y = this.a;
z = this.b;
y[0]++;
z++;
alert('this.a[0] = ' + this.a[0] + '\nthis.b = ' + this.b)
}
}
SPC.t();
SPC.t();
</script>
Running it in your browser will display two alert boxes with:
this.a[0] = 11
this.b = 10
and
this.a[0] = 12
this.b = 10
The question is, why does the value of this.a[0] increment? I'm assigning "y = this.a" and updating element of "y" as "y[0]++;"?
At the same time, exactly the same thing is happening with "b": "z = this.b; z++". Yet, "this.b" remains equal to 10.
How can I change value of "y[0]" in the local scope without affecting "this.a"?
Any ideas?
Thanks!

a is an array, and you're simply copying a reference to the array into y. You need to copy the array a's contents into a new array y instead (using Array.slice() (y = a.slice() in your case) is the easiest way).
(Or, if you only need a[0], you can set y = a[0]. Subsequent changes to y will not affect a[0], since you are copying the value.)
See the "Javascript Arrays Are Assigned By Reference" and "Passing Arrays As Values" sections of this article for more information.

Try Array.slice() function.
y = this.a.slice()
This will create a copy of a array and assign it to y. So modification of y won't affect a.

you are assigning the address value of array a and b into y and z.
therefore, y, and z become the exact copy of a and b.
instead of assigning address value into y and z.
you just need to take content value of a and b and assign them into y and z
y = a[0]
z = b[0]
and then y++

Related

Operator precedence ' ++ ' JavaScript [duplicate]

In JavaScript you can use ++ operator before (pre-increment) or after the variable name (post-increment). What, if any, are the differences between these ways of incrementing a variable?
Same as in other languages:
++x (pre-increment) means "increment the variable; the value of the expression is the final value"
x++ (post-increment) means "remember the original value, then increment the variable; the value of the expression is the original value"
Now when used as a standalone statement, they mean the same thing:
x++;
++x;
The difference comes when you use the value of the expression elsewhere. For example:
x = 0;
y = array[x++]; // This will get array[0]
x = 0;
y = array[++x]; // This will get array[1]
++x increments the value, then evaluates and stores it.
x++ evaluates the value, then increments and stores it.
var n = 0, m = 0;
alert(n++); /* Shows 0, then stores n = 1 */
alert(++m); /* Shows 1, then stores m = 1 */
Note that there are slight performance benefits to using ++x where possible, because you read the variable, modify it, then evaluate and store it. Versus the x++ operator where you read the value, evaluate it, modify it, then store it.
As I understand them if you use them standalone they do the same thing. If you try to output the result of them as an expression then they may differ. Try alert(i++) as compared to alert(++i) to see the difference. i++ evaluates to i before the addition and ++i does the addition before evaluating.
See http://jsfiddle.net/xaDC4/ for an example.
I've an explanation of understanding post-increment and pre-increment. So I'm putting it here.
Lets assign 0 to x
let x = 0;
Lets start with post-increment
console.log(x++); // Outputs 0
Why?
Lets break the x++ expression down
x = x;
x = x + 1;
First statement returns the value of x which is 0
And later when you use x variable anywhere, then the second statement is executed
Second statement returns the value of this x + 1 expression which is (0 + 1) = 1
Keep in mind the value of x at this state which is 1
Now lets start with pre-increment
console.log(++x); // Outputs 2
Why?
Lets break the ++x expression down
x = x + 1;
x = x;
First statement returns the value of this x + 1 expression which is (1 + 1) = 2
Second statement returns the value of x which is 2 so x = 2 thus it returns 2
Hope this would help you understand what post-increment and pre-increment are!
var a = 1;
var b = ++a;
alert('a:' + a + ';b:' + b); //a:2;b:2
var c = 1;
var d = c++;
alert('c:' + c + ';d:' + d); //c:2;d:1
jsfiddle
var x = 0, y = 0;
//post-increment: i++ returns value then adds one to it
console.log('x++ will log: ', x++); //0
console.log('x after x++ : ', x); //1
//pre-increment: adds one to the value, then returns it
console.log('++y will log: ', ++y); //1
console.log('y after ++y : ', y); //1
It is clearer and faster to use ++i if possible :
++i guarantees that you are using a value of i that will remains the same unless you change i
i++ allows to use a value of i which will change in the "near future", it is not desirable if possible
Of course, it's not really much faster, only a little.

Why javascript object value is changed? [duplicate]

This question already has answers here:
Modifying a copy of a JavaScript object is causing the original object to change
(13 answers)
Closed 3 years ago.
Can anyone explain to me why the output value is changed to "20, 2" instead of the original "1, 2"?
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<p id="demo1"></p>
<script>
var x = {
a: 1,
b: 2
};
var y = x;
y.a = 20;
document.getElementById("demo").innerHTML = x.a;
document.getElementById("demo1").innerHTML = x.b;
</script>
</body>
</html>
You are pointing y to the reference of x which itself is pointing to the object {a:1,b:2}.
So in memory it is:
x --> {a:1,b:2}
After you do y = x, it becomes:
y --> x --> {a:1,b:2}
Or to put it simply:
x --> {a:20,b:2}
^
|
y -------
Now when you do y.a = 20, since y and x are both pointing to the same object when properties of the object is changed through either of the references x or y the change will be reflected in both the references:
y --> {a:20,b:2}
^
|
x -------
That is why you get 20,2 when you get x.a.
var y=x
In the above line y is passed the reference of x instead of the whole object x. Any changes made to the object will get reflected in all the variables containing the reference of the object.
Because its the same reference (same address for memory location where the object is stored) both x and y are now the same reference so changing one will change the value stored, and now as they are the same reference they will output the same object values.
I would add something extra to make this answer more productive.
Shallow -Copy
Shallow copy is a bit-wise copy of an object. A new object is created
that has an exact copy of the values in the original object. If any of
the fields of the object are references to other objects, just the
reference addresses are copied i.e., only the memory address is
copied.
example
let x={"a":1,"b":2};
let y=x; //It makes a copy of the reference to x into y
So, the addresses of x and y will be the same i.e. they will be pointing to the same memory location.
so if you do this
y.a=9;
and now when you print y on the screen
console.log(y) // it prints {"a":9,"b":2};
but the interesting fact here is , when you print x
console.log(x) // it also prints {"a":9,"b":2};
So Now how to change this scenario??. The solution is a deep copy
Deep copy
A deep copy copies all fields and makes copies of dynamically
allocated memory pointed to by the fields. A deep copy occurs when an
object is copied along with the objects to which it refers.
in Lehman terms you create a variable y allocate it a different memory location, copy all the members of x, assign the copied members to y
the easiest way to do it is by stringifying the object
let y=JSON.parse(JSON.stringify(x))
now if we do
y.a=9
and print y
console.log(y) // it prints {"a":9,"b":2};
and if we print x
console.log(x) // it prints {"a":1,"b":2};
/// shallow copy
let x = {
"a": 1,
"b": 2
};
let y = x;
y.a = 9;
console.log(y);
console.log(x);
// Deep Copy
let z = {
"a": 1,
"b": 2
};
let t = JSON.parse(JSON.stringify(z));
t.a = 9;
console.log("z:", z);
console.log("t:", t);
This scenario becomes more fun when we have nested objects
let c = {
"a": {
"A": 1
},
"b": {
"B": 2
}
};
let t = Object.assign({}, c); // It is also shallow copying
t.a.A = "7"; // since a is a nested object so again reference is passed
console.log(c);
console.log(t)
console.log("Second Scenario-------------------")
let d = {
"a": {
"A": 1
},
"b": {
"B": 2
}
};
let k = JSON.parse(JSON.stringify(d));
k.a.A = 88
console.log(d)
console.log(k)
That is because y & x both point to same memory location.If you want a separate copy , then deep copy the object. JSON.parse & JSON.stringify
var x = {
a: 1,
b: 2
};
var y = JSON.parse(JSON.stringify(x));
y.a = 20;
document.getElementById("demo").innerHTML = x.a;
document.getElementById("demo1").innerHTML = x.b;
<p id="demo"></p>
<p id="demo1"></p>

In which order are variables assigned in Javascript?

Apparently this is identical in my Firebug console:
var x = "A", y = x;
x + y === "AA";
and
var x = y, y = "A";
x + y === "AA";
Is this standard ECMAScript behaviour, that the order doesn't play a role in comma-separated var assignments?
Edit: The "mystery" is solved. I tested the first example first, then cleared the console and ran the second. However, at this time, y and x were already defined. If you run the JSFiddle provided by David Thomas you always get an "undefinedA". Case settled.
var x = y; will raise an exception if y is not defined.
However, the window object is the default context for Javascript interpreters embedded in browsers. If you previously issued:
y = "A";
Then you actually assigned "A" to window.y, therefore var x = y; becomes valid and assigns window.y to x.

Why is the U variable set to NULL in this interesting Javascript code fragment?

i have a javascript code fragment as
var u = {};
var x = y = z = {"cvalue":"cell", "call":function(){alert(this.cvalue);}};
(function(){u=x;/*change all cvalue in x,y, z, u*/ u.cvalue = "notcell";})();
if(u == x && x == y && y == z && z == u){
u.call();
}
//only u goes to null
u = null;
//x,y,z stay same
alert(x.cvalue);
wondering why u = null only applies for u?
Variables don't actually hold an object, but simply hold a reference to one. By assigning u to null, you're dropping the reference that u had to the object.
A more basic example:
var x = { 'name': 'Bob' };
var y = x;
console.log(x); // Object { name="Bob"}
console.log(y); // Object { name="Bob"}
y.name = 'Jack';
console.log(x); // Object { name="Jack"}
console.log(y); // Object { name="Jack"}
x = null;
console.log(x); // null
console.log(y); // Object { name="Jack"}
Note how our object isn't held in x. It's held somewhere in memory, and x is referring to it. When we do y = x, we copy the reference to y, and therefore y begins to refer to the same object. Setting x to null simply drops the reference that x holds to the object, leaving the actual object unaffected. If we were to set y to null, or to anything else, the garbage collector would eventually pick up the object for destruction.
Daniel is right, but you have to be careful because in Javascript you are sometimes dealing with a copy, and othertimes dealing with the original. For example...
var a = new Object();
a.foo = new function(){alert("I exist")};
var b = a;
b.foo = null;//this erases the function from both a and b (technically, there is only one since a and b point to the same place in memory).
a.foo();//this now fails since there is no longer a function called foo
b = null;//this does NOT affect a in any way as per Daneiel Vassallo's explanation.
You are assigning the exact same object to x, y and z, not a copy of it's value, but the exact same object.
In pseudo code:
var u = OBJECT_A // u points to OBJECT_A
var x = y = z = OBJECT_B // x y and z points to OBJECT_B
(function(){
u=x; // Drop reference to OBJECT_A and point to OBJECT_B
/*change all cvalue in x,y, z, u*/
u.cvalue = "notcell"; //Changes the cvalue in OBJECT_B
// Remember x,y,z, and u points to OBJECT B
// so x.cvalue, y.cvalue, z.cvalue and u.cvalue is the same
})();
if(u == x && x == y && y == z && z == u){
u.call();
}
//only u goes to null
u = null; // Drop reference to OBJECT_B and point to NULL.
//x,y,z still points to OBJECT_B
alert(x.cvalue);

++someVariable vs. someVariable++ in JavaScript

In JavaScript you can use ++ operator before (pre-increment) or after the variable name (post-increment). What, if any, are the differences between these ways of incrementing a variable?
Same as in other languages:
++x (pre-increment) means "increment the variable; the value of the expression is the final value"
x++ (post-increment) means "remember the original value, then increment the variable; the value of the expression is the original value"
Now when used as a standalone statement, they mean the same thing:
x++;
++x;
The difference comes when you use the value of the expression elsewhere. For example:
x = 0;
y = array[x++]; // This will get array[0]
x = 0;
y = array[++x]; // This will get array[1]
++x increments the value, then evaluates and stores it.
x++ evaluates the value, then increments and stores it.
var n = 0, m = 0;
alert(n++); /* Shows 0, then stores n = 1 */
alert(++m); /* Shows 1, then stores m = 1 */
Note that there are slight performance benefits to using ++x where possible, because you read the variable, modify it, then evaluate and store it. Versus the x++ operator where you read the value, evaluate it, modify it, then store it.
As I understand them if you use them standalone they do the same thing. If you try to output the result of them as an expression then they may differ. Try alert(i++) as compared to alert(++i) to see the difference. i++ evaluates to i before the addition and ++i does the addition before evaluating.
See http://jsfiddle.net/xaDC4/ for an example.
I've an explanation of understanding post-increment and pre-increment. So I'm putting it here.
Lets assign 0 to x
let x = 0;
Lets start with post-increment
console.log(x++); // Outputs 0
Why?
Lets break the x++ expression down
x = x;
x = x + 1;
First statement returns the value of x which is 0
And later when you use x variable anywhere, then the second statement is executed
Second statement returns the value of this x + 1 expression which is (0 + 1) = 1
Keep in mind the value of x at this state which is 1
Now lets start with pre-increment
console.log(++x); // Outputs 2
Why?
Lets break the ++x expression down
x = x + 1;
x = x;
First statement returns the value of this x + 1 expression which is (1 + 1) = 2
Second statement returns the value of x which is 2 so x = 2 thus it returns 2
Hope this would help you understand what post-increment and pre-increment are!
var a = 1;
var b = ++a;
alert('a:' + a + ';b:' + b); //a:2;b:2
var c = 1;
var d = c++;
alert('c:' + c + ';d:' + d); //c:2;d:1
jsfiddle
var x = 0, y = 0;
//post-increment: i++ returns value then adds one to it
console.log('x++ will log: ', x++); //0
console.log('x after x++ : ', x); //1
//pre-increment: adds one to the value, then returns it
console.log('++y will log: ', ++y); //1
console.log('y after ++y : ', y); //1
It is clearer and faster to use ++i if possible :
++i guarantees that you are using a value of i that will remains the same unless you change i
i++ allows to use a value of i which will change in the "near future", it is not desirable if possible
Of course, it's not really much faster, only a little.

Categories

Resources