---
# System prepended metadata

title: 'JavaScript: by value, by reference'
tags: [JavaScript]

---

# JavaScript: by value, by reference

Primitives => Pass by value
Objects => Pass by reference

```javascript=
// by value (primitives)
var a = 3;
var b;

b = a;
a = 2;

console.log(a); // 2
console.log(b); // 3

// by reference (all objects (including functions))
var c = { greeting: 'hi' };
var d;

d = c;
c.greeting = 'hello'; // mutate

console.log(c); // {greeting: "hello"}
console.log(d); // {greeting: "hello"}

// by reference (even as parameters)
function changeGreeting(obj) {
  obj.greeting = 'Hola'; // mutate
}

changeGreeting(d);
console.log(c); // {greeting: "Hola"}
console.log(d); // {greeting: "Hola"}

// equals operator sets up new memory space (new address)
c = { greeting: 'howdy' };
console.log(c); // {greeting: "howdy"}
console.log(d); // {greeting: "Hola"}
```

※ **例外注意 Pass by sharing**
```javascript=
var coin1 = { value: 10 };

function changeValue(obj) {
  obj = { value: 123 };
}

changeValue(coin1);
console.log(coin1); // 此時 coin1 仍是 { value: 10 }
```

```javascript=
var coin1 = { value: 10 };

function changeValue(obj) {
  // 僅更新 obj.value，並未重新賦值
  obj.value = 123;
}

changeValue(coin1);
console.log(coin1); // 此時 coin1 則會變成 { value: 123 }
```


###### tags: `JavaScript`