Reputation: 159
Hi I have the following function
var f = {i:0};
var t=0;
function change(f, t) {
f.i++;
t++;
}
change(f,t);
When I console log is seen the values "f = {i:1}, t=0" May I know how there is 1 is added to i and not in t? Any idea guys? I am totally lost here.
Upvotes: 1
Views: 53
Reputation: 4577
The is because JavaScript objects are passed by reference while scalar values are passed by value.
So when you pass in objects to functions and mutate them directly you are actually referencing the same object in memory.
var f = {
i: 0
};
var t = 0;
function change(f, t) {
f.i++;
t++;
console.log(f, t);
}
change(f, t);
console.log(f, t);
To avoid accidentally mutating your object, you will have to create a new instance of the object before performing operations on it. There are multiple ways to accomplish this:
function({...f}, t)
Object.assign()
f
in your function to a destructured f
(f = {...f};
)For example:
var f = {
i: 0
};
var t = 0;
function change(f /*{...f}*/, t) {
f = { ...f};
// Or alternatively,
// f = Object.assign({}, f);
f.i++;
t++;
console.log(f, t);
}
change(f, t);
console.log(f, t);
It is worth noting that re-assigning your object will not update the value. Please take a look into Call by sharing.
var f = {
i: 0
};
var t = 0;
function change(f, t) {
f = {i: 1};
t++;
console.log(f, t);
}
change(f, t);
console.log(f, t);
Upvotes: 2