Call by Value & Call by Reference in Javascript

We are familiar with 2 parameters calling methods in programming languages such as C: called by value or by reference. Basically if you want to change the value of the original variables outside the function, you need to call by reference, or you can just call by value.

To specify the calling method we use, we can do like this:

1
2
3
4
5
6
7
8
9
10
void function foo(int a, int * b) {
a = 1; // a is called by value
*b = 1; // b is called by reference
}

int a = 0, b = 0;
foo(a, &b);

// a = 0, unchanged
// b = 1, changed by foo()

However, in Javascript, there is no pointer variable, so can we still do these 2 calling methods? The answer is yes and actually Javascript takes care that for you for different type of variables.

1
2
3
4
5
6
7
8
9
10
11
12
function foo(arr, obj) {
arr[0] = 1;
obj.a = 1;
}

var arr = [0, 0];
var obj = {a: 0};

boo(arr, obj);

// arr = [1, 0]
// obj = {a: 1}

In fact, only Array and Object in Javascirpt are called by reference, others type of variables are call by value. If you do really want to change a normal variable outside function, you do nothing but remember to declare it before function calling.

Javascript knows how to get global variables.

1
2
3
4
5
6
7
8
function boo() {
a = 1;
}

var a = 0;
boo();

// a = 1

分享到 評論