[JS] 짧고 간결하고 청결한 JS 코드를 작성하는 10가지 팁/ 번역

10 Modern JavaScript Tricks Every Developer Should Use/ Haseeb Anwar를 번역한 글이다.
This post is translated from 10 Modern JavaScript Tricks Every Developer Should Use/ Haseeb Anwar

백엔드의 코드 흐름은 보통 다 비슷하다. 프레임워크, 디자인패턴이 같으면 정말 똑같다. 여기서 사람마다 실력 차이가 드러나는 것이 있다면, 요소요소에서 js 코드들이 아주 필요한만큼만 딱 깔끔하게 작성하는 것이다. 지역변수도 최소화되어있고, 각 언어만의 기본 제공 도구들을 정말 잘 이용해서 코드가 작성되어있다. 아주 기초적인 것부터 얘기하자면 if문으로 확인하는 대신에 || 연산자를 이용하는것을 예로 들수 있겠다. 이번 글을 통해 자신의 프로젝트에 바로 적용할 수 있는 JS 팁들이 있나 알아보자.

1. 조건부로 property를 객체에 추가한다.

const condition = true;

const person = {
    id: 1,
    name: 'John Doe',
    ...(condition && { age: 16 }),
}

&& 연산자는 조건이 true이면 &&연산자 뒤에있는 값을 반환한다. 다만 spread(...) 연산자를 같이 써주어야 한다. false가 결과라면 아무것도 하지 않는다.


2. 객체의 property가 존재하는지 확인.

in keyword를 객체의 property가 존재하는지에 쓸수 있다는 걸 아는 사람?

const person = { name: 'John Doe', salary: 1000 };

console.log('salary' in person); // return true
console.log('age' in person); // return false


3. 객체의 동적 속성 이름 Dynamic Property names in Ojbects

대괄호를 이용해서 간단히 객체에 동적 키를 설정할 수 있다. “동적”이라는 키워드가 들어가면 “바뀔수 있는”이라는 의미로 생각하면 편하다. 기존 key에 대괄호를 추가해서 이용하면 된다.

const dynamic = 'flavour';

var item = {
    name: 'Biscuit',
    [dynamic]: 'Chocolate'
}

console.log(item); // { name: 'Biscuit', flavour: 'Chocolate' }

const dynamic을 바꿀 때마다 key가 바뀌게 된다. (나는 실무에서 써본적이 없어서 이게 중요한가 싶긴하다..)


4. 객체 구조 분해 할당 with 동적키 /Object Destructuring With a Dynamic Key

: 표기법을 이용해서 변수를 구조 분해하고 이름을 변경할수 있는 걸 아는 사람?

먼저 구조분해와 함께 이름을 바꾸는 법을 알아보자. (destructring with aliases)

const person = { id: 1, name: 'John Doe' };

// #1
const { name: personName } = person;

console.log(name) // undefined
console.log(personName); // returns 'John Doe'

“#1” 코드는 아래 코드와 결과가 같다.

const person = { id: 1, name: 'John Doe' };

const name = person;
const personName = name;
const name = undefined;

console.log(personName); // returns 'John Doe'

(이것도 어디서 쓸런지 내실력으론 잘 모르겠다.)

이번엔 동적키와 함께.

const templates = {
  'hello': 'Hello there',
  'bye': 'Good bye'
};
const templateName = 'bye';
const { [templateName]: template } = templates;
console.log(template) // returns 'Good bye'


5. Nullish 통합, “??” 연산자.

?? 연산자는 변수가 null 혹은 undefined인지 확인할 때 이용할 수 있다. 왼쪽 피연산자가 null이거나 undefined이라면 오른쪽 피연산자가 리턴된다. 그렇지 않다면 왼쪽 피연산자가 리턴된다.

const foo = null ?? 'Hello';
console.log(foo); // returns 'Hello'

const bar = 'Not null' ?? 'Hello';
console.log(bar); // returns 'Not null'

const baz = 0 ?? 'Hello';
console.log(baz); // returns 0

마지막 예제 0이 피연산자일 때가 핵심이다. JS 에서 0falsy로 판단된다. 그러나 nullundefined가 아니다. falsy를 이용하려면 널리 이용되고 있는 || 연산자를 이용하자

const cannotBeZero = 0 || 5;
console.log(cannotBeZero); // returns 5

const canBeZero = 0 ?? 5;
console.log(canBeZero); // returns 0


6. 선택적 체인 Optional chaining (?.)

당신은 TypeError: Cannot read property 'foo' of null이란 에러를 싫어할 것이 분명하다. JS개발자에게 고통스러운 일이다. Optional chaining이 이를 위해 소개되었다.

const book = { id: 1, title: 'Title', author: null };

// 일반적으로 이렇게 할 것이다.
console.log(book.author.age); // throws error
console.log(book.author && book.author.age); // returns null (no error)

// optional chaing을 이용하면 이렇게 된다.
console.log(book.author?.age); // return undefined

// 혹은 더 깊은 optional chaning
console.log(book.author?.address?.city);


7. !!을 이용한 참거짓 변환

!! 연산자를 이용하면 참 거짓을 반대로 바꿀 수 있다.

const greeting = 'Hello there!';
console.log(!!greeting) // returns true

const noGreeting = '';
console.log(!!noGreeting); // returns false


8. 문자열과 숫자 변환 String and Integer Conversions

+ 연산자를 이용해서 문자열을 숫자로 바꾼다.

const stringNumber = '123';

console.log(+stringNumber); // returns integer 123
console.log(typeof +stringNumber); // returns 'number'

반대로 숫자에서 문자열은 + 연산자와 ""빈 문자열을 이용한다.

const myString = 25 + '';

console.log(myString); // returns '25'
console.log(typeof myString); // returns 'string'

이 방식의 문자열 <-> 숫자 변환이 아주 편하지만 가시성은 떨어지므로 프로덕션에선 고민해보고 쓰자.


9. Array에서 Falsy 값 확인

filter, some, every와 같은 Array 메서드와 친숙할 것이다. 그러나 Boolean메소드또한 truthy값을 확인할때 아주 우용하다.

const myArray = [null, false, 'Hello', undefined, 0];

// filter falsy 값은 걸른다.
const filtered = myArray.filter(Boolean);
console.log(filtered); // returns ['Hello']

// 하나 이상의 값이 truthy인지 확인한다.
const anyTruthy = myArray.some(Boolean);
console.log(anyTruthy); // returns true

// check if all values are truthy
const allTruthy = myArray.every(Boolean);
console.log(allTruthy); // returns false


10. Array 평탄화 Flattening Arrays of Arrays

배열안에 배열이 있다면 .flat() 메서드를 통해 한겹의 배열을 없애고 편탄하게 만들 수 있다.

const myArray = [{ id: 1 }, [{ id: 2 }], [{ id: 3}]];

const flattedArray = myArray.flat();
// returns [ { id: 1 }, { id: 2 }, { id: 3 } ]

평탄화하는 배열의 깊이를 설정할 수도 있다. .flat() 의 인자로 전달하면 된다.

const arr = [0, 1, 2, [[[3, 4]]]]

console.log(arr.flat(2)); // returns [0, 1, 2, [3,4]]

References