[Javascript] 자바스크립트 프로처럼 쓰는 팁

Yeojin Choi·2021년 10월 5일
1

Javascript

목록 보기
1/11

Conditional(Terary) Operator

조건 ? 조건이 true 시(truthy) 실행할 표현식 : 조건이 false 시(falsy) 실행할 표현식

  • truthy : falsy 로 정의되지 않은 모든 값
  • falsy : false, 0, -0, 0n, "", null, undefined, and NaN

사용처

  • null,undefined value handling
    let greeting = person => {
    	let name = person ? person.name : `stranger`
    	return `Howdy, ${name}`
    }
  • conditional chains : 삼항 연산자는 오른쪽 결합이기 때문에 if-else 처럼 연결될 수 있다.
    function example() {
    	return condition1 ? value1
         : condition2 ? value2
         : condition3 ? value3
         : value4;
    }

Nullish Coalescing Operator

leftExpr ?? rightExpr
왼쪽 피연산자가 null 이거나 undefined 일 경우 오른쪽 피연산자 반환
cf) || ( or 연산자) : null, undefined + 거짓

사용처

  • 기본값 제공
const nullValue = null;
const emptyText = ""; // falsy
const someNumber = 42;

const valA = nullValue ?? "default for A";
const valB = emptyText ?? "default for B";
const valC = someNumber ?? 0;

console.log(valA); // "default for A"
console.log(valB); // "" (as the empty string is not null or undefined)
console.log(valC); // 42
  • null, undefined handling
let count = 0;
let text = "";

// ||
let qty = count || 42;
let message = text || "hi!";
console.log(qty);     // 42
console.log(message); // "hi!"

// ??
qty = count ?? 42;
message = text ?? "hi!";
console.log(qty);     // 0
console.log(message); // ""

Object Destructing(비구조화 할당)

//Bad
const name = person.name;
const age = person.age;

//Object Destucting
const {name, age} = person;

Spread Syntax (전개 연산자)

Spread Syntax 객체

const item = {type: 'pants', size: '26'};
const detail = {price : 3000}

// item객체, detail 에 있는 모든 속성을 가진 객체를 가지고 싶다면?

//Bad
const myPants = {
	type : item.type,
  	size : item.size,
  	price : detail.price
}

//Good : Object.assign 활용
const myPants = Object.assign({},item,defail)

//Better : Spread Syntax
const myPants = {...item, ...detail}

// 가격만 5000원으로 바꾸고 싶다?
const myPants = {...item, ...detail , price: 5000}

Spread Syntax 배열

const arr = ["a","b","c"];

//arr.push("d") 맨 뒤에 삽입
arr = [...arr, "d"]; // "a", "b", "c", "d"

//arr.unshift("e") 맨 앞에 삽입
arr = ["e", ...arr]; // "e", "a", "b", "c", "d"

// concat 배열을 합쳐 새로운 배열 반환
const arr2 = ["A","B"];
let combined = arr.concat(arr2);
combined = [...arr, "가", ...arr2];

Optional Changing (?.)

참조의 유효성을 확인할 필요 없이 객체의 속성 확인 가능

template literals

Loops

async await

참고 : 자바스크립트 프로처럼 쓰는 팁 ✨

profile
프론트가 좋아요

0개의 댓글