모던 자바스크립트 복습 #2

dldzm·2021년 8월 16일
0

Javascript 기본

목록 보기
7/9

벨로퍼트와 함께하는 모던 자바스크립트
React로 넘어가기 전에 빠르게 JavaScript를 복습해본다.

2장 알고있으면 유용한 자바스크립트 문법

01. 삼항 연산자

삼항 연산자를 중첩해서 사용할 수도 있다.
조건 ? true일때 : false일때 를 기반으로

const cond1 = false;
const cond2 = false;

const value = cond1 ? '와우!' : cond2 ? 'blah' : 'foo';

console.log(value);	// foo

cond1이 false 이므로 와우!cond2 ? 'blah' : 'foo' 덩어리 중에 뒷 부분을 받는다. cond2 ? 'blah' : 'foo'를 받았을 때, cond2가 false 이므로 blah와 foo 중 foo를 받는다.

✔️ 하지만 삼항 연산자를 쓰는 것보다 if 문으로 처리하는게 코드 읽기가 더 쉽다.

02. Truthy and Falsy

주어지지 않는 object를 접하려고 하면 오류가 뜬다. 문제가 있다고 콘솔에 출력해야 하는 상황이라면 다음과 같이 구현한다.

undefined이거나 null인 상황을 대비하기 위해 다음과 같이 코드를 작성한다.

function print(p){
  if(!p){
    return;
  }
  console.log(p.name);
}

undefinednullFalsy한 값이다.
Falsy한 값은 이외에도 다음과 같다.

이 외의 값은 모두 Truthy한 값이다.

✔️ 값이 있다면 Truthy하게 받는다는 것.

console.log(!3);	//false
console.log(![]);	//false

삼항 연산자를 사용하면 쉽게 value 값의 존재 유무에 따라 쉽게 truefalse로 전환이 가능하다.

value의 값이 존재하므로 Truthy로 들어간다.

03. 단축 평가(short-circuit evaluation) 논리 계산법

&&

const dog = {
  name : '댕댕'
};

function getName(animal){
  if(animal){
    return animal.name;
  }
  return undefined;
}

const name = getName();
console.log(name);	//undefined

여기서 함수를 단축시키기 위해 &&를 사용해보자.

function getName(a){
  return a && a.name;
}

a가 존재하지 않는 값이라면 undefined값이 뜰 것이다. && 연산자로 인해 undefined값이 곱해지면 결과는 항상 undefined이므로 결과는 undefined로 나온다.

||

function getName(animal){
  const name = animal && animal.name;
  if(!name){
    return "이름이 없는 동물이다.';
  }
  return name;
}

function getName(animal){
  const name = animal && animal.name;
  return name || '이름이 없는 동물이다';
}

04. 함수의 기본 파라미터

입력인자에 기본값을 설정하는 다양한 방법이 있다.

  1. const radius = r || 1 과 같이 ||를 사용한다.
  2. function calculate(r=1)과 같이 선언한다. 다음은 ES6에서 부터 사용 가능하다.
  3. const calculate = (r=1) => Math.PI*r*r;과 같이 화살표 함수에서도 사용할 수 있다.

05. 조건문 더 스마트하게 쓰기

만약 value값이 1이거나 2이거나 3이거나 4라면 이렇게 접근한다면 ||문을 나열하기보다 const arr = [1,2,3,4]을 선언하고 arr.includes(value)하는 것이 더 깔끔하다.

화살표 함수를 사용한다며느

const isAnimal = name => [1,2,3,4].includes(name);

과 같이 사용할 수 있다.

function getSound(animal){
  const sounds = {
    a : 1,
    b : 2,
    c : 3,
    d : 4
  };
  return sounds[animal] || "...?";
}

06. 비구조화 할당 (구조분해) 문법

✔️ 구조 분해 할당 구문은 배열이나 객체의 속성을 해체하여 그 값을 개별 변수에 담을 수 있게 하는 JavaScript 표현식입니다.

var a, b;

[a=5, b=7] = [1];
console.log(a); // 1
console.log(b); // 7

다음 코드는 animal 객체 안에 있는 name을 nickname으로 선언하겠다는 것이다.

const animal = {
  name: '멍멍이',
  type: '개'
};

const { name: nickname } = animal;

배열 비구조화 할당

비구조화 할당은 객체 뿐만 아니라 배열에서도 할 수 있다.

const array = [1, 3];
const [one, two = 2] = array; // 3이 주어지지 않았다면 2로 지정된다.

console.log(one);
console.log(two);

깊은 값 비구조화 할당

const deep = {
  state : {
	information : {
      name = 'ink',
      lang = ['cpp', 'python', 'javascript']
    }
  },
  day : 16
};

여기서 name, lang, day 값을 꺼내고 싶을 때,

  1. 비구조화 할당 문법을 2번 사용한다.
const {name, lang} = deep.state.information;
const day = deep.day;

const extracted = {
  name, lang, day
};
  1. 한번에 모두 호출한다.
const {
  state : {
    information : {name, lang}
  },
  day
} = deep;

const extracted = {
  name, lang, day
};

07. spread와 rest

spread

✔️ spread...를 통해 구현 가능하며 객체 혹은 배열을 펼칠 수 있다.

const slime = {
  name : 1
};

const cuteslime = {
  ...slime,
  attr : 2
};

const redcuteslime = {
  ...cuteslime,
  color : 3
};

console.log(redcuteslime)	// {name: 1, attr: 2, color: 3}

rest

✔️ rest는 객체, 배열, 그리고 함수의 파라미터에서 사용이 가능하다. ...rest, last 이렇게 역순으로는 선언할 수 없다.

const num = [0,1,2,3,4,5];

const [one, ...rest] = numbers;

console.log(one);	//0
console.log(rest);	//1,2,3,4,5

함수의 파라미터가 몇개가 될 지 모르는 상황에서 rest 파라미터를 사용하면 오류를 피할 수 있다.

function sum(...rest){
  return rest.reduce((acc, current) => acc+current, 0);
}

//여기서 sum의 입력 파라미터는 7개이다.
const result = sum(1, 2, 3, 4, 5, 6);
console.log(result);	// 21

퀴즈) 최대값 가져오기

function max(...rest) {
  let max = 0;
  return rest.reduce((acc, current) => {
    if (max < current){
      max = current;
    }
    return max;
  }, 0 );
}

const result = max(1, 2, 3, 4, 10, 5, 6, 7);
console.log(result);
function max(...nums){
  return nums.reduce((acc,current) => (current > acc ? current : acc), nums[0]);
}

08. 자바스트립트의 Scope에 대한 이해

  1. Global scope : 전역
  2. Function scope : 함수
  3. Block scope : 블록

참고 - let, var, const 차이

Hoisting

✔️ Hoisting이란 자바스크립트에서 아직 선언되지 않는 함수/변수를 끌어올려서 사용할 수 있는 자바스크립트의 작동 방식이다.

var에서 동작하지만, constlet은 hoisting이 발생하지 않고 에러가 발생한다.

profile
🛰️ 2021 fall ~

0개의 댓글