I created a simple function and I noticed something unexpected about javascript. When I pass a variable in to a function, then change it, its not changing outside that function. Heres some code:
function check(val, isEven) {
if (val % 2 === 0){
isEven++;
console.log('incremented isEven is ', isEven);
}
}
var arr = [1, 2, 3, 4, 5, 6, 7, 8];
var isEven = 0;
for (var x = 0; x < arr.length; x++) {
check(arr[x], isEven);
console.log('isEven is now ', isEven);
}
Fiddle is here.
Maybe I've been misinterpreting Javascript all these years, but I would have expected the isEven
within check()
to be the same as the original isEven
.....But you can see in the logs, outside isEven
stays as 0....