About pass by reference in Javascript


#1

Look at this code:

let hi={
a:1,
b:2
}
function hello(obj){
  obj.c=3
}
hello(hi);
console.log(hi);// { a: 1, b: 2, c: 3 }
let hey={
a:1,
b:2
}
function aloha(obj){
  obj={
    a:1,
    b:2,
    c:3
  }
}
aloha(hey);
console.log(hey);// { a: 1, b: 2 }
hey={
  a:1,
  b:2,
  c:3
}
console.log(hey);//{ a: 1, b: 2, c: 3 }

why aloha(hey) cannot change hey’s property,
but hello(hi) can?


#3

and this exactly why you shouldn’t modify global variable within a function, return exist for a reason.

hello function adds a property to the global object, while aloha creates a new local object


#4

Thank you;) So you mean by definition function cannot rewrite a complete object? what’s the mechanism behind?


#5

its certainly possible to rewrite the complete object:

function aloha(){
  return {
    a:1,
    b:2,
    c:3
  }
}

hey = aloha()

now we update the dictionary (stored in hey variable) within its own global scope.