개발 언어/자바스크립트 33가지 개념

[JavaScript 33가지 개념] 03. 값 타입(Value Type)과 참조 타입(Reference Type)

우주다람쥐 2021. 5. 18. 18:14
반응형

 

JavaScript 는 객체 지향 언어이다. 즉, JavaScript의 대부분은 Object (객체) 이다.

객체가 아닌 유일한 요소는 Primitive Type (원시 자료형) 이다.

 

둘 사이의 차이점 중 하나는 기본 데이터 유형이 값(Value) 으로 전달되고 객체가 참조(Reference) 로 전달된다는 것 이다.

 

예시를 통해 비교해보면 다음과 같다.

let name = 'Carlos';
const firstName = name;
name = 'Color';

console.log(name);		// Color
console.log(firstName);		// Carlos

const myName = {
  firstName: 'Carlos',
};
const identity = myName;
myName.firstName = 'Color';

console.log(myName.firstName);		// Color
console.log(identity.firstName);	// Color

 

String은 원시 자료형이므로 값 타입(Value Type)이다. 그래서 값은 복사되어 적용되며, 적용한 원본 변수의 값을 변경했을 때 사본은 적용되지 않는다.

그러나 Object는 참조 타입(Reference Type)이므로 원본이 변경되면 사본도 동일하게 변경된다.

 

배열(Array)과 함수(Function)도 object이므로 동일하게 참조 타입이다.

const a = []; 
const b = a;
a.push (1);

console.log (a); 	// [1] 
console.log (b); 	// [1] 
console.log (a === b); // true

 

변수의 타입에 따라 값이 적용되고 저장되는 형태가 다릅니다.

개발 시 이런 차이를 명확히 알고 상황에 맞는 타입을 사용해야 합니다.

 

 

참고 자료

- https://hackernoon.com/grasp-by-value-and-by-reference-in-javascript-7ed75efa1293

 

Grasp “By Value” and “By Reference” in JavaScript | Hacker Noon

Grasp “By Value” and “By Reference” in JavaScript And learn why it’s crucial to know the difference https://unsplash.com/ JavaScript is an Object-Oriented language: this means that most things in JavaScript are Objects. For example, functions are

hackernoon.com

- https://medium.com/dailyjs/back-to-roots-javascript-value-vs-reference-8fb69d587a18

 

Back to roots: JavaScript Value vs Reference

Let’s look at the concept of Value vs Reference. Every JavaScript developer should know this topic as it’s often the reason behind bugs in…

medium.com

 

반응형