개발/JavaScript

[JavaScript] 객체의 프로퍼티 표기법: Obj.prop vs. Obj[prop_name]

김알리 2021. 9. 17. 15:21
728x90
반응형

객체와 그 프로퍼티에 접근하는 두 가지 방법이 있다.
첫째는 Object.property_name의 형태로 표기하는 Dot Notation이고,
둘째는 Object[property_name]의 형태로 표기하는 Bracket Notation이다.
두 경우 모두 객체와 프로퍼티를 표현하는 것은 맞으나, 꼭 알고 사용해야 할 차이점들이 있어서 정리해 보았다.

DOT NOTATION (Object.property_name)

MDN에서는 다음과 같이 정리한다.

1. Property must be a valid JavaScript identifier.
2. In the ECMAScript standard, the names of properties are technically "IdentifierNames", not "Identifiers", so reserved words can be used but not recommended.


해석 하자면
1. 프로퍼티 이름은 제대로 된 자바스크립트 식별자여야 한다. 즉, Object.$1 은 허용되지만 Object.1 은 허용되지 않는다.
2. 프로퍼티 이름은 엄밀히 따지자면 "Identifier"가 아니라 "IdentifierNames"이다. 그러므로 예약어(reserved name)도 프로퍼티의 이름으로 사용할 수는 있으나 추천하지는 않는다. (여기서 예약어란 우리가 흔히 알고 있는 new, break, if, else, for, while, return 등의, 자바스크립트가 이미 찜해놓고 사용하고 있는 단어들이다.)


그렇다면 Identifier와 IdentifierNames의 차이점은 무엇일까? (ES5 깃허브 링크)

Identifier Names are tokens that are interpreted according to the grammar given in the “Identifiers” section of chapter 5 of the Unicode standard, with some small modifications. An Identifier is an IdentifierName that is not a ReservedWord.


즉,
1. Identifier Names는 우리가 흔히 알고 있는 식별자로, '유니코드 스탠다드의 문법에 맞춰서 해석되는 토큰'이다.
2. Identifier는 예약어가 아닌 IdentifierName이다.

 

 

 

BRACKET NOTATION (Object[property_name])

MDN에서는 이렇게 설명한다.

In the object[property_name] syntax, the property_name is just a string or Symbol. So, it can be any string, including '1foo', '!bar!', or even ' ' (a space).


즉, 바로 프로퍼티 이름이 string 혹은 Symbol이라는 것이다.
다른 부분은 Dot Notation과 똑같으나 이 부분 때문에 코드가 완전히 달라질 수 있다.
obj.1은 허용되지 않지만 obj[1]은 허용된다. [] 내부의 1은 숫자가 아니라 문자열인 "1"로 인식되기 때문이다.
이것 때문에 Array에서 arr[1]과 같이 숫자를 바로 사용하여 프로퍼티에 접근할 수 있다. (자바스크립트의 Array는 엄밀히 따져서 Object이다)


앞에서 봤듯, Dot Notation의 Object.property_name에서 property_name은 IdentifierName이다.
아래 두 코드 블록을 보자.
아래는 주어진 string에 각 알파벳이 몇 번 등장하는지 세어서 countChar이라는 객체에 저장하기 위한 코드이다.

// DOT NOTATION 

const str = "hello" 
const countChar = {} 

for (let char of str) { 
	if (countChar.char) { 
    	countChar.char++ 
    } else { 
    	countChar.char = 1 
    } 
} 

console.log(countChar); // { char: 5 }


Dot Notation의 경우이다.
for...of 문에서 이미 선언된 char이 있지만, countChar.char에서는 countChar이라는 객체 내부의 char 프로퍼티를 따로 생성하였다.
countChar.char의 char은 countChar이라는 객체의 프로퍼티의 IdentifierName이기 때문이다.

// BRACKET NOTATION 
const str = "hello" 
const countChar = {} 
for (let char of str) { 
	if (countChar[char]) { 
    	countChar[char]++ 
    } else { 
    	countChar[char] = 1 
    } 
} 

console.log(countChar); // { e: 1, h: 1, l: 2, o: 1 }


Bracket Notation의 경우이다.
for...of 문에서 이미 선언된 char이 string 타입이다.
때문에 countChar 객체는 char이라는 IdentifierName에 할당된 각 알파벳을 프로퍼티 이름으로 사용했다.
str이 string 타입이 아닌 number로 이루어진 Array라도 마찬가지이다.
그런 경우 countChar 객체는 숫자를 string 타입으로 바꿔서 프로퍼티 이름으로 사용할 것이다.

반응형


요약하자면,
1. Dot Notation의 프로퍼티 이름은 식별자이다. 따라서 이미 같은 이름으로 선언된 다른 변수가 있더라도 그대로 객체의 프로퍼티의 이름으로 사용한다.
2. Bracket Notation의 프로퍼티 이름은 string 혹은 Symbol이다. 따라서 이미 같은 이름으로 선언된 다른 변수가 있다면 그 변수에 할당된 값을 객체의 프로퍼티 이름으로 사용한다.

728x90
반응형