0

why the result of this function is not 1?

   
function call(t) {
    t = 1;
};

var b = 0;

call(b);

console.log(b)
Anna
  • 19
  • 3

2 Answers2

2

Parameters are passed by value, not by reference. From MDN:

Primitive parameters (such as a number) are passed to functions by value; the value is passed to the function, but if the function changes the value of the parameter, this change is not reflected globally or in the calling function.

Klaycon
  • 10,599
  • 18
  • 35
1

Because b is not directly accessed by the function when calling it. b is used as a parameter for the function, but it doesn't change the original varible.

The function is just changing the value, which is passed to the function inside the function. If you would like to change the variable b, you would need something like this:

var b = 0;

function call() {
    b = 1;
}

call();

console.log(b);

In this case b is 1 after execution of the function (because it referenced the variable b directly).

JKD
  • 1,279
  • 1
  • 6
  • 26