0

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....

Mark
  • 4,428
  • 14
  • 60
  • 116
  • 5
    primitives are not passed by reference, you get a "fresh copy" that's scoped to the function. But note that your function does not do what you claim it does in your code: you've called it `check` but instead of returning some truth value, you're making it modify a value. Keep it `check`, and simply have it return whether an action needs to be taken or not. – Mike 'Pomax' Kamermans Mar 15 '16 at 23:23
  • 1
    JavaScript is purely pass-by-value, so a *copy* of the value of `isEven` is passed to the function. – Pointy Mar 15 '16 at 23:25
  • This is how C family languages work. If you want a variable altered by a function (1) the function has to assign to a variable like **y=f(x)** and (2) the function needs a **return** statement near the end to return a computed value. – Arif Burhan Mar 15 '16 at 23:26

1 Answers1

2

In JavaScript, objects are passed by copying the reference to the object. Primitive types (string/number/etc) are passed by value.

This means if you passed in an object, modifying the object within the function would be reflected outside the function as inside and outside would both have references to the same object.

With a primitive type, the variable is copied when it is passed in and changes inside the function will no longer be reflected in the variable outside the function.

Ted A.
  • 2,264
  • 17
  • 22