Home Javascript 꼭 알아야 할 ES6+ 문법
Post
Cancel

Javascript 꼭 알아야 할 ES6+ 문법

인프런 파이썬/장고 웹서비스 개발 완벽 가이드 with 리액트 강의를 보고 정리한 내용입니다.


var 대신 let과 const를 사용

var를 사용하면 Javascript의 호이스팅 때문에, 변수 관리에 예기치 않은 혼란이 생길 수 있음

왜냐하면, var 변수를 선언하기 전에 호출을 하고, 그 이후에 호출을 해도 ReferenceError가 발생하기 않기 때문

그에 반해 letconst는 block scope를 갖고 있기 때문에, 호이스팅이 발생하지 않음 → 선언을 해야만 사용을 할 수 있음 (의도치 않게 역순서 (호출→선언)로 사용해서 변수를 혼동해서 사용하는 것을 미연에 방지할 수 있음)

예) 호이스팅 예시

1
2
3
4
5
6
7
8
9
10
11
12
console.log(name);
var name = "jaeho";

// 위 코드는 호이스팅에 의해 실은 아래 코드와
// 동일하게 동작함

var name;
console.log(name);
name = "jaeho";

// 만약 아래에 "var name='jaeho'"코드가 없다면
// ReferenceError가 발생하게 됨

let과 const의 차이

let: Lexical Variable Scoping을 지원하는 변수 선언 문법. 재할당 가능

Lexical Scope는 함수와 변수의 Scope를 선언된 위치를 기준으로 정함

const: let과 달리 상수문법이기 떄문에 선언한 값을 재할당할 수 없음. 내부 속성값은 수정 가능

  • 이와 같은 특성 덕분에, const 문법을 잘 활용하면 버그 발생률을 줄일 수 있음
1
2
3
4
5
6
7
//불가능
const hobby = 'soccer'
hobby = 'basketball'

//가능
const tom = {'hobby:'soccer'}
tom.hobby = 'basketball'

Object 선언

Object 선언 (1/3)

Key 따옴표

파이썬과 달리, key에 따옴표를 넣어도 안 넣어도 똑같음

1
2
3
4
5
6
7
8
9
//tom1과 tom2는 동일

let tom1={
	name='tom'
}

let tom2={
	'name'='tom'
}

Object 선언 (2/3)

Key 계산이 필요한 경우 []로 묶어줘야 함

[ ] 라고 해서 Array문법은 아님

연산을 하는 경우

1
2
3
const tom = {
  ["score" + "1"]: 100,
};

변수를 key로 사용하는 경우

1
2
3
4
const key = "location";
const tom = {
  [key]: "seoul",
};

Object 선언 (3/3)

단축 속성명

key랑 value가 값이 같을 경우, 하나로 통일해서 적어도 됨

함수의 경우에도 key:value 형태가 아니라 그냥 함수를 선언해주듯이 적으면 됨

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//아래 두 변수는 동일

let tom1 = {
  name: name,
  print: function () {
    console.log();
  },
};

let tom2 = {
  name,
  print() {
    console.log();
  },
};

객체 복사

JS는 Object/Array에 대해서는 대입 시에 얕은 복사 (Shallow Copy)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const obj1 = { value1: 10 };
//얕은 복사
const obj2 = obj1;
//깊은 복사
const obj3 = JSON.parse(JSON.stringify(obj1));

obj1.value += 1; //obj

console.log("obj1:", obj1);
console.log("obj2:", obj2);
console.log("obj3:", obj3);

//결과
//11
//11
//10

Template Literals

backtick과 ${expression}를 사용


비구조화

배열은 [ ]로 묶고, 객체는 { }로 묶음

배열 비구조화

파이썬에서는 좌우항이 개수가 같아야 하지만, Javascript는 달라도 오류가 안남

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//tom이 할당됨
let [name] = ["tom", 10, "seoul"];
//10이 할당됨
let [, age] = ["tom", 10, "seoul"];
//height에 undefined가 할당됨
let [name, age, region, height] = ["tom", 10, "seoul"];
//height은 디폴트값 150
let [name, age, region, height = 150] = ["tom", 10, "seoul"];

//디폴트값 함수
function get_default_value() {
  return 150;
}
let [name, age, region, height = get_default_value()] = ["tom", 10, "seoul"];

객체 비구조화

1
2
3
4
5
6
7
8
9
10
11
12
const tom = {
	name='tom',
	age=10,
	region:"Seoul"
}
// 객체에서 해당 key값의 value를 뽑아냄.
// height은 정의안되어있으니 undefined
const {age,name,height}=tom;

//고전적인 방법
const age = tome.age;
const name = tom.name;

객체의 속성값을 함수의 인자로 사용하고자 할 때

key값을 중괄호로 묶어서 인자로 넘김

1
2
3
4
5
6
7
8
9
10
//동일한 결과가 출력됨
const print_person1 = (person) => {
  console.log(person.name);
};
const print_person2 = ({ name }) => {
  console.log(name);
};

print_person1(tom);
print_person2(tom);

객체가 담긴 배열이 각각 동일한 key값을 가지고 있고 반복문으로 출력하고자 할 떄

1
2
3
4
5
6
7
8
9
10
11
12
const people = [
  { name: "tom", age: 10 },
  { name: "steve", age: 15 },
];
//아래 두 반복문은 동일한 결과
for (const person of people) {
  console.log(person.name, person.age);
}

for (const { name, age } of people) {
  console.log(name, age);
}

전개 연산자 (Spread Operator)

배열

1
2
3
//name에는 첫번째 원소인 Tom이 들어가고,
// rest에는 배열의 나머지 인자가 배열 형태로 들어감
let [name, ...rest] = ["Tom", 10, "Seoul"];
1
2
3
let names = ["Steve", "John"];
let students = ["Tom", ...names, ...names];
//결과: students = ["Tom","Steve","John","Steve","John"]
1
2
3
4
//배열의 인자들을 일일이 안 적고 다 받으려고 할 떄
let printArgs = (...args) => {
  console.log(args);
};

객체 (많이 사용됨)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//속성명이 중복될 경우, 마지막값이 남음

let tom = {
  name: "tom",
  age: 10,
  region: "seoul",
};

let steve = {
  ...tom,
  name: "Steve",
};

// 결과:
// steve = {
//	 age:10,
//	 region:"seoul",
//	 name:"Steve"
//  }

TIP 전개 연산자를 많이 쓰면, 구조가 복잡할 경우, 가독성이 떨어짐. 이 때, immer라이브러리를 쓰는 것이 도움됨

https://github.com/immerls/immer


디폴트값에 함수를 적용할 경우

함수 인자의 기본값으로 디폴트 함수를 지정했을때, nodejs와 python 비교

nodejs

1
2
3
4
//node.js의 경우 get_default_height는 필요할떄마다 호출됨
function say_hello(name,height=get_default_height(){
	console.log('hello')
}

python

1
2
3
4
#파이썬의 경우, 함수가 만들어질때 딱 한번 호출됨
def say_hello(name,height=get_default_height(){
	print'hello')
}

Arrow Function

1
2
3
//return을 안 적어도 구문이 한 줄이라면
// 괄호로 묶거나 안 묶어도 반환됨
const fn = () => ()
  • function(){}을 사용할 경우, this가 내부로 바인딩 됨
  • Arrow Function은 this와 arguments를 바인딩하지 않음❌
This post is licensed under CC BY 4.0 by the author.

React 엘리먼트

React 속성값