> For the complete documentation index, see [llms.txt](https://jen-hsuan-hsieh.gitbook.io/javascript-node-js/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jen-hsuan-hsieh.gitbook.io/javascript-node-js/chapter1/12javascript-quan-gong-lve-ff1a-ke-fu-js-de-qi-guai-bu-fen/123wu-jian-yu-han-shu/1237guan-nian-xiao-ding-ning-ff1a-chuan-zhi-he-chuan-can-kao.md).

# 1.2.3.7.觀念小叮嚀：傳值和傳參考

* 傳值 (By value)
  * 所有純值 (primitive)都是傳值
  * 將值拷貝到不同記憶體地點
  * b = a, 將a的值複製一份到b的記憶體位置, 共兩個記憶體位置
* 傳參考 (By reference)
  * 所有物件(Object)都是傳參考
  * 兩個變數都會參考到相同記憶體位置
  * b = a, b就如同a的別名, 僅一個記憶體位置
* 不可改變的 (Immutable)

```
    //By value (primitive)
    var a = 3;
    var b;

    //By value because a is a primitive
    b = a;
    a = 2;

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

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

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

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

    function changeGreeting(obj){
        obj.greeting = 'hola';
    }

    changeGreeting(d);
    //印出Object {greeting: "hola"}
    console.log(c);
    //印出Object {greeting: "hola"}
    console.log(d);

    //equal operator sets up new memory space (new address)
    c = {greeting: 'howdy'};
    //印出Object {greeting: "howdy"}
    console.log(c);
    //印出Object {greeting: "hola"}
    console.log(d);
```
