본문 바로가기

Programming/JavaScript

Dot vs. Bracket Notation

const sunny = {
    firstName: 'Sunny',
    lastName: 'Ryu',
    age: 2022 - 1988,
    job: 'technical writer',
    hobbies: ['Writing', 'Coding', 'Learning']
};
console.log(sunny);

코드에 작성한 property 순서와는 상관없이 automatically ordered됨

참고로 dot notation에서는 real final name이 필요함

e.g.) sunny.'last' + nameKey 🙅‍♀️

console.log(sunny.lastName);
console.log(sunny['lastName']);
// prints Ryu

 

firstName이랑 lastName에서 Name이 중복되니

nameKey에 담아줌

const nameKey = 'Name';
console.log(sunny['first' + nameKey]); // prints Sunny
console.log(sunny['last' + nameKey]); // prints Ryu
const interestedIn = prompt('What do you want to know about Sunny? Choose between firstName, lastName, age, job, and hobbies');
// console.log(sunny.interestedIn); // undefined
console.log(sunny[interestedIn]); // prints technical writer

dot notation에서는 실제로 존재하는 key명을 적어줘야 함

sunny.interestedIn 이런 식으로 접근 안됨 🙅‍♀️

 

if (sunny[interestedIn]) {
    console.log(sunny[interestedIn]);
} else {
    console.log('Wrong request! Choose between firstName, lastName, age, job, and hobbies')
}

만약 존재하지 않는 key를 입력하면 false이므로 else문이 실행됨!

 

sunny.location = 'Beautiful Seoul';
sunny['linkedIn'] = 'https://www.linkedin.com/in/sunjeongryu/';
console.log(sunny);

새로운 Key로 location과 linkedIn을 입력해주니 object가 업데이트된 걸 알 수 있음!

 

console.log(`${sunny.firstName} has ${sunny.hobbies.length} hobbies, and her favorite hobby is ${sunny.hobbies[0]}`);
// prints Sunny has 3 hobbies, and her favorite hobby is Writing

👏👏👏

 

참고로 operator precedence에서 dot notation인 left-to-right이므로 sunny의 hobbies로 접근할 수 있는거임

'Programming > JavaScript' 카테고리의 다른 글

Coding Challenge #3 - comparing BMIs using objects  (0) 2022.09.15
Object Methods  (0) 2022.09.15
Introduction to Objects  (0) 2022.09.11
Coding Challenge #2 - tip calculator with arrays  (0) 2022.09.10
Basic Array Operations (Methods)  (0) 2022.09.10