JS에서 원시타입과 객체의 차이

원시타입 (Primitive Types):

javascriptconst num = 5;           // number
const text = "hello";    // string  
const flag = true;       // boolean
const empty = null;      // null
const nothing = undefined; // undefined

객체 타입 (Object Types):

javascriptconst arr = [1, 2, 3];          // Array (객체)
const obj = { name: "김철수" };  // Object
const func = function() {};     // Function (객체)
const date = new Date();        // Date (객체)

차이점:

1. 메소드 호출:

javascript// 원시타입인데 메소드가 있는 것처럼 보임 (JavaScript 마법!)
const str = "hello";
console.log(str.toUpperCase()); // "HELLO"
// → JavaScript가 임시로 String 객체를 만들어서 메소드 실행

// 진짜 객체는 메소드가 실제로 있음
const arr = [1, 2, 3];
arr.push(4);  // 진짜 객체의 메소드

2. 저장 방식:

javascript// 원시타입 = 값 자체가 저장됨
let a = 5;
let b = a;    // 5라는 값이 복사됨
a = 10;
console.log(b); // 5 (영향 없음)

// 객체 = 참조(주소)가 저장됨  
let obj1 = { count: 5 };
let obj2 = obj1;    // 같은 객체를 가리킴
obj1.count = 10;
console.log(obj2.count); // 10 (영향 받음!)

3. typeof 결과:

javascriptconsole.log(typeof 5);           // "number"
console.log(typeof "hello");     // "string"
console.log(typeof true);        // "boolean"

console.log(typeof [1,2,3]);     // "object"
console.log(typeof {name: "김철수"}); // "object"
console.log(typeof function(){}); // "function" (특별한 객체)

정리:

객체: 참조, 가변, 공유됨

원시타입: 값 자체, 불변, 복사됨

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *