call by value and call by reference
in Programming on Javascript
Javascript Basic
if data type in var is primitive data, it’s call by value
primitive data Type
- number
- string
- boolean
- null
- undefined
var a = 1;
var b = a;
b = 2 ;
console.log(a); // 1 (call by value)
if data type in var is Object, it’s reference by value
var a = {'id':1};
var b = a;
b.id = 2;
console.log(a.id); // 2 (reference by value)
function and reference
var a = 1;
function func(b){
b = 2;
// call by value
}
func(a);
console.log(a); // 1
var a = {'id':1};
function func(b){
b = {'id:2'};
// b just created a new object so it's not affected to a's value
}
func(a);
console.log(a); // 1
var a = {'id':1};
function func(b){
b.id = 2;
// call by reference
}
func(a);
console.log(a); // 2