Shorthand Properties

ljjunh·2024년 11월 21일

clean-code-javascript

목록 보기
29/38
post-thumbnail

자바스크립트를 사용하다 보면 객체의 속성과 메서드를 정의하는 다양한 방법을 접하게 된다. ES6+에서는 이를 더 간단하게 표현할 수 있는 문법들이 추가되었다. 이 문법들을 제대로 이해하지 못하면 코드를 읽거나 쓸 때 어려움을 겪을 수 있다.

문제 상황

// 이런 코드를 마주쳤을 때
const name = 'JavaScript';
const version = 'ES6';
const features = ['arrow function', 'destructuring'];

const languageInfo = {
    name,
    version,
    features,
    printInfo() {
        console.log(`${this.name} ${this.version}`);
    }
};

이 코드는 ES6+ 문법을 모르는 개발자에게는 다음과 같은 의문점이 생길 수 있다.
1. name : name 이렇게 해야되는거 아닌가?
2. perintInfo(){}는 함수 선언을 잘못한거 아닌가? function 키워드는 어디갔지?
이 코드를 이해하려면 ES6+의 Shorthand Property 문법을 알아야 한다.

Shorthand Property란? 🤔

변수명과 객체의 속성명이 같을 때 사용할 수 있는 축약 문법

// ❌ 일반적인 방식
const name = 'jun';
const age = 20;

const user = {
    name: name,
    age: age
};

// ✅ Shorthand Property 사용
const user = {
    name,    // name: name과 동일
    age      // age: age와 동일
};

Concise Method란? 📝

객체의 메서드를 정의할 때 function 키워드를 생략할 수 있는 축약 문법

// ❌ 기존 방식
const person = {
    firstName: 'junhee',
    lastName: 'lim',
    getFullName: function() {
        return this.firstName + ' ' + this.lastName;
    }
};

// ✅ Concise Method 사용
const person = {
    firstName: 'junhee',
    lastName: 'lim',
    getFullName() {  // function 키워드 생략
        return this.firstName + ' ' + this.lastName;
    }
};

두 문법을 함께 사용하기 🎯

const firstName = 'junhee';
const lastName = 'lim';
const age = 20;

// ✅ Shorthand Property와 Concise Method 함께 사용
const person = {
    firstName,     // Shorthand Property
    lastName,      // Shorthand Property
    age,          // Shorthand Property
    getFullName() {  // Concise Method
        return `${this.firstName} ${this.lastName}`;
    }
};

주의할 점 ⚠️

  1. 코드를 간결하게 만들어주지만, 처음 js를 배우는 사람에게는 혼란을 줄 수 있다.
  2. 팀의 코딩 컨벤션에 따라 일관성 있게 사용해야 한다.
    이러한 모던 JS문법을 이해하면 코드를 더 잘 이해하고 활용할 수 있다.
profile
Hello

0개의 댓글