[JS] 고급진 js 쓰기

j(a)son·2022년 10월 31일
0

알아둬야할 Falsy 값

JavaScript 엔진은 boolean 뿐만아니라 다양한 값들을 Truthy(참으로 평가되는 값), 또는 Falsy(거짓으로 평가되는 값) 으로 구분한다. 조건문이나 반복문 같은 조건식에서는 boolean값으로 평가되는 문맥을 사용해야하는데, 이 때 Truthy는 true로, Falsy값은 false로 암묵적 형변환이 일어난다.

주요 6가지 Falsy 값
false, null, undefined, 0, '', NaN
Truthy 값
Falsy값 이외의 전체 값들

3항 연산자 (Ternary Operator)

// Bad Code
function getResult(score) {
  let result;
  if (score > 5) {
    result = 'good';
  } else if (score <= 5) {
    result = 'bad';
  }
  return result
}

// Good code
function getResult(score) {
  return score > 5 ? 'good' : 'bad';
}

Nullish coalescing operator

// Bad code
function printMessage(text) {
  let message = text;
  if (text == null || text == undefiend) {
    message = 'Nothing to display';
  }
  console.log(message);
}

// Good code
function printMessage(text) {
  const message = text ?? 'Nothing to display'
  console.log(message);
}

a ?? 'sth' -> a가 null or undefined 일 때 'sth' 반환
a ?? 'sth' -> a가 그 이외일 때는 a 반환

Default Parmeter와의 차이점

function printMessage(text = 'Nothing to display') {
  console.log(text);
}

|| && 는?

ex1 && ex2 -> ex1true 인 경우 ex2을 반환하고 그렇지 않은 경우 ex1을 반환
ex1 || ex2 -> ex1true 인 경우 ex1을 반환하고 그렇지 않은 경우 ex2를 반환


nullish coalescing 과 디폴트 파라미터와의 차이는?
디폴트 파라미터는 오로지 undefined에만 디폴트가 적용된다!

Logical OR Operator와의 차이점

leftExpr || rightExpr -> 왼쪽 코드가 falsy 일 때만 우측 실행
leftExpr ?? rightExpr -> 왼쪽 코드가 null or undefined 일 때만 우측 실행

  • 그럼 falsy란??

undefined, null, false, 0, -0, NaN, '', ""

  • Expr의 의미
    표현식!이다. leftExpr의 반환 값이 falsy ??

Object Destructuring(객체 구조분해 - object or array ...etc)

const person = {
  name: 'Julia',
  age: 20,
  phone: '01011111111'
};

const {name, age, phone} = person;

Spread Syntax

const item = {type: 'shirt', size: 'M'};
const detail = {price: 20, made: 'Korea', gender: 'M'};

// 기존 item, detail Object를 내비두면서, 즉 one-depth 깊은복사
const all = {...item, ...detail};
// 또는 Obejct.assign 사용
const all = Object.assign(item, detail);

기존 배열 불변하게 복사하기 (깊은 복사 및 추가)

const a = [1,2,3,4];

a.push(5); // 기존 배열 변했음
const b = [...a, 5]; // 기존 배열 안 변했음
// 결과 : b = [1,2,3,4,5];

a.unshift(5); // 기존 배열 변했음
const b = [5, ...a]; // 기존 배열 안 변했음
// 결과 : b = [5,1,2,3,4];

const c = a.concat([6,7,8]);
// 또는
const c = [...a, '다른 아이템 추가 가능', ...[6,7,8]);

Optional Chaining

const bob = {
  name: 'julia',
  age: 20,
};
const anna = {
  name: 'julia',
  age: 20,
  job: {
    title: 'sw engineer',
  }
};

// Bad code
function displayJobTitle(person){
  if (person.job && person.job.title) {
    console.log(person.job.title);
  }
}

// Good code
function displayJobTitle(person){
  if (person.job?.title) {
    console.log(person.job.title);
  }
}
// job이 있다면 그 안에 있는 title이 있는 지 없는지 검사하고,
// job이 없다면 바로 false 반환


// nullish coleacing 과의 결합
function displayJobTitle(person){
  const title = person.job?.title ?? 'No Job Yet';
  console.log(title);
}

배열 내 중복 제거

const array = [1,2,3,4,1,1,2];
console.log([...new Set(array)]);

자주 사용하는 Array 함수

.filter
.map
.forEach
.reduce
.push
.unshift
...등등 더 많음, 정리 및 추가 예정

드림코딩 JS 프로처럼 쓰기

profile
himynameisjason

0개의 댓글