Dot notation VS Bracket notation

Sunghee Kim·2022년 4월 29일
0

Dot notation:

Property identifies can only be alphanumeric (and and $)
Property identifiers cannot start with a number.
**_Property identifiers cannot contain variables.
**
JS의 key는 기본적으로 string여서 ' '안에 써야 하지만 object에서 안써도 되게 만들었다.

OK — obj.prop_1, obj.prop$
Not OK — obj.1prop, obj.prop name

Ex) myself={
name:'Code Kim',
location:{country:'South Korea',
city:'Seoul'},
age:30,
'cats':['냥순','냥돌']
mykey:'Hello world'
}

let mykey='cats'
console.log(myself['cats'])//['냥순','냥돌']
console.log(myself(['mykey'])//['냥순','냥돌']
----->myself.mykey 이렇게 변수를 dot notation으로는 사용할수 없음.

만약 property중에 mykey:'Hello World'라는 게 있다면
console.log(myself.mykey)라고 하면 //Hello world가 출력된다.
결론, 만약 dot notation+변수 이렇게 쓰이면 일단은 property에서 mykey를 먼저 검색해서 찾아낸다. bracket notation에서는 mykey를 사용했을 때 변수라고 생각한다.

존재하지 않는 key를 찾으려고 하면 undefined가 나온다.

Bracket notation:

Property identifiers have to be a String or a variable that references a String.
It is okay to use variables, spaces, and Strings that start with numbers
OK — obj["1prop"], obj["prop name"]

(출처:https://codeburst.io/javascript-quickie-dot-notation-vs-bracket-notation-333641c0f781)

profile
개발하는 스트롱맘

0개의 댓글