[JS] 자바스크립트로 클린하게 코딩하자(Feat. 유용한/최신 문법)

apro_xo·2021년 11월 27일
0
post-thumbnail

삼항연산자

코드 예시

  1. 기존 코드😡
function getResult(number){
  let result;
  if(number > 5 ) {
    result = '👍';
  }
  else {
    result = '🤷‍♂️'
  }
  return result;
}
  1. 좋은 코드😀
function getResult(number){
  result number > 5 ? '👍' : '🤷‍♂️';
}

Nullish coalescing operator

Nullish coalescing operator의 기본적인 사용 방법은 아래와 같다.

expr1 ?? expr2

코드 예시

  1. 기존 코드😡
 function printMessage(text) {
   let message = text;
   if(text==null || text==undefined) {
     message = "nothing🙄";
   }
   console.log(message);
 }
  1. 좋은 코드😀
 function printMessage(text) {
   const message = text ?? "nothing🙄";
   console.log(message);
 }
  1. 테스트👀
 function printMessage(text) {
   const message = text ?? "nothing🙄";
   console.log(message);
 }

printMessage('hello'); // hello
printMessage(undefined); // nothing🙄
printMessage(null); // nothing🙄

null, undefined을 판별하여 맞으면 ?? 연산자 뒤의 표현식을 반환

default parameter와의 차이점

function printMessage(text="nothing🙄") {
  console.log(text);
}
printMessage('hello'); // hello
printMessage(undefined); // nothing🙄
printMessage(null); // null

default parameter는 undefined인 경우에만 적용된다


Logical OR operator

Nullish coalescing operator 와는 비슷하지만 살짝 다른 문법이다.

expr1 || expr2

expr1이 falsy한 값이면 expr2가 실행된다

falsy ?

  • false
  • undefined
  • null
  • 0
  • -0
  • NaN
  • '' or ""

코드 예시

function printMessage(text) {
  const message = text || "nothing🙄";
   console.log(message);
}
printMessage('hello'); // hello
printMessage(undefined); // nothing🙄
printMessage(null); // nothing🙄
printMessage(0); // nothing🙄
printMessage(''); // nothing🙄

/* 함수인 경우에도 적용 가능 */
const result = getInitialState() || fetchFromServer();
console.log(result); // hello

function getInitialState() {
  return null;
}

function fetchFromServer() {
  return 'hello';
}

Object Destructuring

코드 예시

  1. 기존 코드😡
const person = {
  name:'Julia',
  age:20,
  phone:'121212'
}

function displayPerson(person) {
  display(person.name);
  display(person.age);
  display(person.phone);
}
  1. 좋은 코드😀
const person = {
  name:'Julia',
  age:20,
  phone:'121212'
}

function displayPerson(person) {
  const { name, age, phone } = person;
  display(name);
  display(age);
  display(phone);
}

Spread Syntax - object

코드 예시

  1. 기존 코드😡
const person = {name:'hong', age:52};
const detail = {job:'professor', gender:'male'};

person['job'] = detail.job;
person['gender'] = detail.gender;
  1. 좋은 코드😀
const person = {name:'hong', age:52};
const detail = {job:'professor', gender:'male'};

// 복사, 합치기와 업데이트가 다 가능
const personInfo = {...person, ...detail, age:20};

Spread Syntax - array

코드 예시

  1. 기존 코드😡
let arr = ['apple', 'banana'];
arr.push('tomato');
arr.unshift('grape');
  1. 좋은 코드😀
let arr = ['apple', 'banana'];
let arr2 = ['fork', 'beef'];
arr = [...arr, 'tomato'];
arr = [...arr, ...arr2]; // ['apple', 'banana', 'tomato', 'fork', 'beef']
arr = ['grape', ...arr];
// ['grape', 'apple', 'banana', 'tomato', 'fork', 'beef']

Optional Chaining

코드 예시

  1. 기존 코드😡
const bob = {
  name:'jul',
  age:20
};

const anna = { 
  name:'ann',
  age:20,
  job:{
    title:'Web Programmer'
  }
}

function displayJobTitle(person) {
  if(person.job && person.job.title) {
    console.log(person.job.title);
  }
}
  1. 좋은 코드😀
const bob = {
  name:'jul',
  age:20
};

const anna = { 
  name:'ann',
  age:20,
  job:{
    title:'Web Programmer'
  }
}

function displayJobTitle(person) {
  if(person.job?.title) {
    console.log(person.job.title);   
  }
}
profile
유능한 프론트엔드 개발자가 되고픈 사람😀

0개의 댓글