JavaScript에서 변수의 전달 방법인 pass-by-value, 그리고 또다른 방법인 pass-by-reference에 대한 설명입니다.
Primitive type의 메모리상의 값은 그것의 실제 값입니다(예를 들어, boolean의 경우 true, number의 경우 42). Primitive type은 고정된 크기의 메모리에 저장할 수 있습니다.
Primitive type은 scalar type 또는 simple type으로도 불립니다.
Reference type은 다른 값을 포함할 수 있습니다. Reference type의 내용은 고정된 크기의 메모리에 저장이 불가능하므로, 메모리 상에서의 Reference type의 값은 참조 그 자체(메모리 주소)를 담고 있습니다.
Reference type은 complex type 또는 container type으로도 불립니다.
Copying a primitive:
let a = 13 // assign `13` to `a`
let b = a // copy the value of `a` to `b`
b = 37 // assign `37` to `b`
console.log(a) // => 13
원본이 변하지 않았습니다. 복사본만 변했습니다.
Copying a reference:
let a = { c: 13 } // assign the reference of a new object to `a`
let b = a // copy the reference of the object inside `a` to new variable `b`
b.c = 37 // modify the contents of the object `b` refers to
console.log(a) // => { c: 37 }
메모리 주소를 복사했으므로, 원본 역시 변했습니다.