3 minute read

객체(Object)를 사용할 때 알아두면 유용한 객체 상식 9가지를 소개한다.

상식 1

객체는 참조 타입이다.

참조 타입의 변수는 실제값이 아닌 데이터의 주소값을 저장한다.

const car = {
  name: "Hyundai",
  model: "AVANTE",
  price: 1000,
};

console.log(car);
console.log(typeof(car));

// Expected Output:
// [object Object] {
//   model: "AVANTE",
//   name: "Hyundai",
//   price: 1000
// }
// "object"

상식 2

객체는 0개 이상의 속성으로 이루어져 있다.

객체의 속성은 “key(속성 이름)”와 “value(속성 값)”로 구분된다.

객체 외부에서는 객체이름과 속성이름을 통해 속성값에 접근할 수 있다.

const car = {
  name: "Hyundai",
  model: "AVANTE",
  price: 1000,
};

car.model = "SONATA";
console.log(car.model);

// Expected Output:
// "SONATA"

상식 3

객체를 선언할 때 보통 const 키워드를 사용한다.

const의 특징을 확인해보자.

이유는 간단하다. 객체의 재정의를 막기 위해서이다.

재정의는 불가능하지만 Dot notation과 Bracket notation을 통해 속성에 접근 및 생성, 수정, 삭제가 가능하다.

속성에 접근하는 대표적인 2가지 방법:

  • Dot Notation
    • 일반적으로 많이 사용하는 접근법
    • ex) objectName.propertyName
    • 단, 띄어쓰기 같은 자바스크립트의 식별자로 허용되지 않는 문자를 포함할 경우 반드시 Braket Notation을 통해 속성에 접근해야 한다.
  • Braket Notation
    • 어떠한 스타일의 속성 이름에도 접근할 수 있다.
    • ex) objectName[“propertyName”]
const car = {
  name: "Hyundai",
  model: "AVANTE",
  price: 1000,
};

// car = {
//   name: "Audi",
//   model: "A3",
//   price: 2000,
// }; // "TypeError: Assignment to constant variable.

car.year = 2020;
car["VIN"] = 43987298;

console.log(car);

// Expected Output:
// [object Object] {
//   model: "AVANTE",
//   name: "Hyundai",
//   price: 1000,
//   VIN: 43987298,
//   year: 2020
// }

상식 4

속성의 이름에는 명명 규칙(Naming Convention)이 존재하지 않는다.

따라서 어떠한 스타일로도 속성 이름을 지어줄 수 있다.

<예시>

  • 띄어쓰기(space): 띄어쓰기를 사용할 경우 큰따옴표(““)로 문자열처럼 감싸주어야 한다.
  • 정수(integer): 정수를 사용할 경우 자동으로 문자열로 변환된다.
  • 예약어(reserved word): 독자에게 혼돈을 줄 수 있으니 사용을 삼가한다.
const car = {
  "car name": "Hyundai",
  "car model": "AVANTE",
  "car price": 1000,
  123: 123,
  for: true,
};

console.log(car);

// Expected Output:
// [object Object] {
//   123: 123,
//   car model: "AVANTE",
//   car name: "Hyundai",
//   car price: 1000,
//   for: true
// }

상식 5

하나의 객체에 여러가지 데이터 타입의 값들을 저장할 수 있다.(객체, 배열, 함수 포함)

아래의 예시는 위의 설명을 증명하기 위한 것이다.

const car = {
  name: "Hyundai",
  model: "AVANTE",
  price: 1000,
  options: {
    color: ["red", "blue", "yellow"],
    getColor: function(c){
      return c;
    },
  },
};

let carColor = car.options.getColor(car.options.color[0]);
console.log(carColor);

// Expected Output:
// "red"

상식 6

객체 메서드란 객체내에 정의된 함수이다.

객체 메서드를 생성하는 방법은 객체의 속성이름에 함수의 정의를 대입하면 된다.

함수 내에 사용하는 “this” 키워드는 해당 객체를 가리킨다.

const car = {
  name: "Hyundai",
  model: "AVANTE",
  price: 1000,
  getCar: function(){
    return this.name + " " + this.model + " " + this.price;
  }
};

console.log(car.getCar());

// Expected Output:
// "Hyundai AVANTE 1000"

상식 7

객체에 특정 속성의 존재 여부를 확인하는 방법

Syntax: “propertyName” in objectName;

존재 여부에 따라 boolean값을 반환한다.

const car = {
  name: "Hyundai",
  model: "AVANTE",
  price: 1000,
  getCar: function(){
    return this.name + " " + this.model + " " + this.price;
  }
};

console.log("name" in car);
console.log("price " in car); // price 끝에 띄어쓰기에 주의!!

// Expected Output:
// true
// false

상식 8

객체 속성(key/value)을 삭제하는 방법

<Syntax>

  • delete objectName.propertyName;
  • delete objectName[“propertyName”];
const car = {
  name: "Hyundai",
  model: "AVANTE",
  price: 1000,
  getCar: function(){
    return this.name + " " + this.model + " " + this.price;
  }
};

delete car.name;
delete car["model"];

console.log(car);

// Expected Output:
// [object Object] {
//   getCar: function(){
//     return this.name + " " + this.model + " " + this.price;
//   },
//   price: 1000
// }

상식 9

for…in()은 객체에만 사용하는 것을 권장한다.

더 정확히 말하면 for…in()을 배열에 사용하는 것을 권장하지 않는다.

그 이유는 for…in()의 속성에 대한 순회는 “임의로” 정해지기 때문이다.

배열은 기본적으로 순서를 중요시 하는 객체임을 명심해야 한다.

이 때문에 배열의 속성이름(index)이 정수로 지정되는 것이다.

그와 반대로 객체의 속성이름은 문자열로 이루어져 순서가 없으며 어떠한 규칙도 없다.

배열의 속성(요소)을 일관된 순서로 반복하고 싶다면 일반 for문이나 forEach(), for…of()를 사용하는 것이 적합하다.

for…in()의 실질적인 목적은 객체의 속성을 확인하기 위해서이다. 또한 디버깅을 할 때 유용하게 사용된다.

const car = {
  name: "Hyundai",
  model: "AVANTE",
  price: 1000,
  getCar: function(){
    return this.name + " " + this.model + " " + this.price;
  }
};

for(prop in car){
  console.log(prop + ": " + car[prop]);
}

// Expected Output:
// "name: Hyundai"
// "model: AVANTE"
// "price: 1000"
// "getCar: function(){
//     return this.name + \" \" + this.model + \" \" + this.price;
//   }"

Leave a comment