TIL 17 | 모던 프로퍼티 표기법

CHAEIN·2021년 6월 25일
0

JavaScript

목록 보기
17/31
post-thumbnail

기존 프로퍼티 표기법

const user = {
  title: 'Codeit',
  birth: 2007,
  job: '프로그래밍 강사'
}

모던한 프로퍼티 표기법

1. 변수에 할당된 값을 이용해서 프로퍼티 만들기

const title = 'Codeit'
const birth = 2007
const job = '프로그래밍 강사'

const user = {
  title: title,
  birth: birth,
  job: job,
} // {title: "Codeit", birth: 2017, job: "프로그래밍 강사"}

이때 활용하는 변수의 이름과 프로퍼티의 이름이 같다면 하나만 작성하는 표현이 가능해진다.

const user = {
  title,
  birth,
  job,
} 

console.log(user) // {title: "Codeit", birth: 2017, job: "프로그래밍 강사"}

2. 함수 프로퍼티 표기법
프로퍼티 네임과 값으로 사용할 변수나 함수의 이름이 같다면 중복해서 작성하지 않고 하나만 작성할 수 있다.

function getFullName(){
  return `${this.firstName} ${this.lastName}`
}

// 기존 표기법
const user = {
  firstName: 'Tess',
  lastName: 'Jang',
  getFullName: getFullname,
}

// 모던한 표기법
const admin = {
  firstName: 'Alex',
  lastName: 'Kim',
  getFullName
}

객체 내부에서 메소드를 선언할 때 콜론과 function 키워드를 생략할 수 있다.

// 기존 표기법
const user = {
  firstName: 'Tess',
  lastName: 'Jang',
  getFullName: function(){
    return `${this.firstName} ${this.lastName}`
  }
}

// 모던한 표기법
const user = {
  firstName: 'Tess',
  lastName: 'Jang',
  getFullName (){
    return `${this.firstName} ${this.lastName}`
  }
}

프로퍼티 이름을 표현식으로 사용하는 법

const propertyName ='birth'
const getJob = () => 'job'

const user = {
  ['Code' + 'it'] : 'Modern JavaScript',
  [propertyName]: 2017,
  [getJob()]: '프로그래밍 강사',
}

console.log(user.job) // 값을 프로퍼티로 활용하면 .을
console.log(user[getJob()]) // 표현식을 프로퍼티로 활용하면 []을

null 병합 연산자 ??

null 병합 연산자(nullish coalescing operator) ?? 를 사용하면 짧은 문법으로 여러 피연산자 중 그 값이 ‘확정되어있는’ 변수를 찾을 수 있다.

a ?? b // a가 null 도 아니고 undefined도 아니면 a, 그 외의 경우는 b

X = a ?? b // x = (a !== null && a !== undefined) ? a : b;


// 변수 중 실제 값이 있는 변수의 값을 출력하는데, 세 변수 모두 값이 없다면 '익명의 사용자’가 출력되도록 한다면?
let firstName = null;
let lastName = null;
let nickName = "바이올렛";

alert(firstName ?? lastName ?? nickName ?? "익명의 사용자"); // 바이올렛

옵셔널 체이닝 연산자

옵셔널 체이닝(optional chaining) ?.을 사용하면 프로퍼티가 없는 중첩 객체를 에러 없이 안전하게 접근할 수 있습니다.

// 예시 1
function printCatName(user) {
  console.log(user.cat.name);
}

const user1 = {
  name: 'Captain',
  cat: {
    name: 'Crew',
    breed: 'British Shorthair',
  }
}

printCatName(user1); // Crew

만약 프로퍼티를 가지고 있지 않은 경우라면? 에러가 난다.

const user2 = {
  name: 'Young',
}

console.log(user2.cat); // undefined
printCatName(user2); // TypeError: Cannot read property 'name' of undefined

cat 프로퍼티를 가지고 있지 않은 user2는 cat 프로퍼티가 undefined이기 때문에 user2.cat.name에 접근하려는 순간 에러가 발생하게 된다. 그래서 printCatName과 같이 중첩된 객체의 프로퍼티를 다룰 때는 user.cat.name에 접근하기 전에 user.cat이 null 혹은 undefined가 아니라는 것을 검증하고 접근해야 에러를 방지할 수 있다. 이때 사용할 수 있는 것이 옵셔널 체이닝 연산자이다.

function printCatName(user) {
  console.log(user.cat?.name);
}

옵셔널 체이닝 연산자는 왼편의 프로퍼티 값이 undefined 또는 null이 아니라면 그다음 프로퍼티 값을 리턴하고 그렇지 않은 경우에는 undefined를 반환하는 문법이다.

// 옵셔널 체이닝 연산자의 작동 원리를 표현한 삼항 연산자
function printCatName(user) {
  console.log((user.cat === null || user.cat === undefined) ? undefined : user.cat.name);
}
// 옵셔널 체이닝 연산자와 null 병합 연산자와 결합
function printCatName(user) {
  console.log(user.cat?.name ?? '함께 지내는 고양이가 없습니다.');
}

const user2 = {
  name: 'Young',
}

printCatName(user2); // 함께 지내는 고양이가 없습니다.

0개의 댓글