변수의 전달(Passing Variables)

마데슾 : My Dev Space·2019년 11월 5일
0

[CODESTATES]PRE

목록 보기
9/19

JavaScript에서의 Primitive Types & Reference Types

JavaScript에서 변수의 전달 방법인 pass-by-value, 그리고 또다른 방법인 pass-by-reference에 대한 설명입니다.

알아야 할 것들

  • JavaScript에는 두가지 종류의 변수 타입이 있습니다: primitive, reference
  • 변수가 생성되고 난 후, 고정된 크기의 메모리가 예약이 됩니다.
  • 변수를 복사한 후, 고유의 메모리값은 복사됩니다.
  • 호출을 통해 변수를 함수에 전달하면, 해당 변수의 복사본이 생성됩니다.

Primitive Types (원시 타입)

Primitive type의 메모리상의 값은 그것의 실제 값입니다(예를 들어, boolean의 경우 true, number의 경우 42). Primitive type은 고정된 크기의 메모리에 저장할 수 있습니다.

  • null
  • undefined
  • Boolean
  • Number
  • String

Primitive type은 scalar type 또는 simple type으로도 불립니다.

Reference Types

Reference type은 다른 값을 포함할 수 있습니다. Reference type의 내용은 고정된 크기의 메모리에 저장이 불가능하므로, 메모리 상에서의 Reference type의 값은 참조 그 자체(메모리 주소)를 담고 있습니다.

  • Array
  • Object
  • Function

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 }

메모리 주소를 복사했으므로, 원본 역시 변했습니다.

profile
👩🏻‍💻 🚀

0개의 댓글