I am sure this is very simple but I can't get seem to get this to work just right. Here is my code:
var zero = 10;
function some(elem, num) {
return elem += num;
}
console.log(some(zero, 10));
console.log(some(zero, 10));
console.log(some(zero, 10));
From what I understand, I was expecting the variable in zero
to increase each time by 10.. So, it would be 10, 20 and 30. Instead, I keep getting 10. Obviously, this isn't right.
My question is, how would I increase the variable zero
by 10 each time and save that value back to the variable zero
?
I am sure this is very simple but I can't get seem to get this to work just right. Here is my code:
var zero = 10;
function some(elem, num) {
return elem += num;
}
console.log(some(zero, 10));
console.log(some(zero, 10));
console.log(some(zero, 10));
From what I understand, I was expecting the variable in zero
to increase each time by 10.. So, it would be 10, 20 and 30. Instead, I keep getting 10. Obviously, this isn't right.
My question is, how would I increase the variable zero
by 10 each time and save that value back to the variable zero
?
5 Answers
Reset to default 9JavaScript passes by value, so modifying the passed value won't have any effect on the caller's variable. You'd need to use the return value:
var zero = 10;
function sum(elem, num) {
return elem + num;
}
console.log(zero = sum(zero, 10));
console.log(zero = sum(zero, 10));
console.log(zero = sum(zero, 10));
When you do
elem += num
...in your function, you're incrementing the value held by the elem
argument passed to the function, not the variable that argument's value came from. There is no link between the argument elem
and the variable zero
, the value of zero
, as of the call to some
, gets passed into the function.
Primitives like number are passed by value not by reference. It means that you increment the local elem
variable, not the zero
ones.
So, you need – outside the function – to reassign zero
after each call of the function:
console.log(zero = some(zero, 10));
Or, makes zero a property of an object, an pass the object. Objects are passed by reference, and not value. So, for instance:
var zero = [10]
function some(elem, num) {
return elem[0] += num;
}
console.log(some(zero, 10));
console.log(some(zero, 10));
console.log(some(zero, 10));
That's because zero
nows is not a primitive, but an Array, and arrays are objects and therefore passed by reference.
Try this:
sum = (function sum(num){
var zero = 0;
return function () {
return zero += num;
};
})(10);
console.log(sum());
console.log(sum());
console.log(sum());
zero = some(zero, 10)
You return the new value in some(). So you have to assign it to zero after the function call.