[TIL] Javascript 최신 문법 정리

kiyeol·2021년 2월 12일
1
post-thumbnail

자바스크립트 문법 정리

Shorthand property names

Key와 Value가 동일한 경우에는 하나로만 생략이 가능하다.

const obj = {
	name: name,
    	age: age,
}
const obj = {
	name,
    	age,
}

Destructuring assignment

객체나 배열을 분해해서 그 값을 개별 변수에 담을 수 있게 하는 JavaScript 표현식

const obj = {
	name: 'Kim',
    	age: 20,
}
{
	const {name, age} = obj
    	console.log(name, age) // Kim, 20

}

Spread Syntax

copy할 때 많이 쓰이며, ... 을 이용해 배열이나 객체에 들어 있는 하나하나 씩을 낱개로 가져와서 복사해온다.

const first = { key: 'key1' };
const second = { key: 'key2' };
const array = [first, second];

const arrayCopy = [...array]
const arrayCopy2 = [...array, { key: 'key3' }]; //add

first.key = 'newKey' // 주소 값만 복사되기 때문에 실제로 전부 다 동일한 obj를 가르키고 있다.

Default parameters

함수를 호출 할 때 아무런 인자를 전달되지 않을 때 기본인 초깃값을 지정할 수 있다.

 function defaultMessage(message = 'default message') {
      console.log(message);
    }
    

Ternary Operator

삼항연산자를 이용해 if문을 축약할 수 있다.

isValidEmailReg && isValidPwReg
      ? onEmailLogin()
      : alert("이메일 또는 비밀번호가 일치하지 않습니다.");

Template Literals

백틱(``)을 이용해 표기하는 내장된 표현식을 허용하는 문자열 리터럴이다.
${}을 이용해 자바스크립트 문법을 표현할 수 있다.

const hi = `안녕하세요. 저는 ${name} 입니다.`;

optional chaining

?.를 이용해 프로퍼티가 없는 중첩 객체를 에러(TypeError) 없이 안전하게 접근할 수 있는 연산자이다.

const user = {name: {first: "John", last: "Doe"}}

> user?.name?.first
'John'
> user?.address?.street
undefined

Nullish Coalescing Operator

?? 를 이용해 논리 연산자로 왼쪽 피연산자가 null이나 undefined일 때, 오른쪽 피연산자를 return한다.

false: false, '', 0, null, undefined

기본 값을 지정할 떄 || 연산자를 사용하지만 이것을 사용하면 버그가 일어날 수 있다.

 {
    const name = '';
    const userName = name || 'Guest';
    console.log(userName); //Guest

    const num = 0;
    const message = num || 'undefined';
    console.log(message); //undefined
  }

//Nullish Coalescing Operator

  {
    const name = '';
    const userName = name ?? 'Guest';
    console.log(userName); // ''

    const num = 0;
    const message = num ?? 'undefined';
    console.log(message); // 0
  }

출처)
https://github.com/dream-ellie/learn-javascript/tree/master/notes/es6-11

https://developer.mozilla.org/ko/

profile
kyday63@gamil.com

0개의 댓글