4 minute read


1. ES6

ES는 ECMAScript(에크마스크립트)의 준말로 ECMAScript International에서 표준화 한 스크립팅 언어이다.

지금에 와서는 자바스크립트 = ES라고 봐도 무방하며 이중 ES6 이상을 우리는 모던 자바스크립트라고 부르고 있다.



2. ES6 문법

2.1 변수 선언

ES5의 변수 선언은 오로지 var로 가능하다. 재할당과 재선언에 자유로운 편이지만 호이스팅 문제가 있다.

호이스팅?
코드가 실행되기 전에 변수선언/함수선언이 해당 유효범위의 최상단으로 끌어 올려진 것과 같은 현상을 말한다.

하지만 ES6에서는 var의 유연한 특성으로 인해 발생할 수 있는 피해를 방지하기 위해 let과 const를 사용해서 변수를 선언할 수 있다

2.1.1. let

let은 중복선언이 불가능하지만 재할당이 가능하다.

1
2
3
4
5
6
7
8
let name = "moya";
console.log(name);  //result : moya

let name = "ddd";
//result : Uncaught SyntaxError: Identifier 'name' has already been declared

name = "kkk";
console.log(name);  //result : kkk

위와 같이 최초에 let으로 name을 선언하고 값을 할당한 뒤 let으로 같은 이름인 name을 선언하고 값을 할당하면 에러가 발생하지만 단순히 값만 재할당하는 경우는 정상적으로 사용이 가능하다.

2.1.2 const

const는 중복선언과 재할당이 모두 불가능하다.

1
2
3
4
5
6
7
8
9
10
11
12
const name;   
//result : Uncaught SyntaxError: Missing initializer in const declaration

const name = "moya";
console.log(name);  //result : moya

const name = "ddd";   
//result : Uncaught TypeError: Assignment to constant variable.

name = "kkk";
console.log(name);  
//result : Uncaught SyntaxError: Identifier 'name' has already been declared

const의 경우에도 역시 중복선언이 불가능하지만 let과 다르게 재할당 역시 불가능 하므로 선언과 동시에 초기화가 진행되어야 하는점에 주의가 필요하다.
하지만 단순 재할당을 금지할 뿐 불변을 의미하는 것은 아니므로 const로 선언한 객체의 값은 재할당이 가능하다.


2.2 화살표 함수

ES6부터 생긴 새로운 함수 선언방법이다.
화살표 함수의 특징은 일반적으로 함수의 자신을 호출하는 객체를 가리키는 dynamic this와 달리 코드의 상위 스코프를 가리키는 lexical this를 가진다.
또한 화살표 함수를 사용하면 일반적인 함수 선언 방식과 return 에서 차이를 보인다. 일반적인 함수 선언 방식에서는 return을 선언해야 값을 받을 수 있는 반면, 화살표 함수를 사용하면 return 없이 값을 돌려 받을 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//ES5 함수선언
var func = function(arg){
  console.log("ES5")
};

//ES6 화살표 함수선언
var func = arg => {
  console.log("ES6");
};

//인자가 2개 이상인 경우 괄호로 감싸서 사용
var func = (arg1, arg2) => {
  console.log("ES6");
};

//this의 경우 상위 스코프를 가리킨다.
var text = {
  name: "moya",
  food: ["pizza, chicken", "pasta"],
  ateFood() {
    this.food.forEach(item =>
      console.log(this.name + " ate " + item));
  }
}


2.3 템플릿 리터럴

백틱(`)을 사용해서 문자열을 표기하는 방법이다.
문자열 안에 ${}를 사용해서 코드를 삽입할 수 있으며 이 자바스크립트 코드가 반환하는 값을 문자열에 삽입할 수 있다.

1
2
3
4
5
6
7
8
9
//ES5 
var name = "moya"
var age = 20
console.log("이름 : " + name + ", 나이 : " + age);

//ES6
let name = "moya"
let age = 20
console.log("이름 : ${name}, 나이 : ${age}.");


2.4 Destructuring(디스트럭처링)

배열이나 객체에서 필요한 요소만 추출하여 할당하고 싶은 경우에 사용할 수 있다.

1
2
3
4
  const arr = [1,2,3];
  const [one, two, three] = arr;

  console.log(one, two, three);     //result : 1 2 3;

위와 같이 사용할 수 있고 배열의 길이가 서로 다른 경우 할당 받지 못한 변수는 undefined가 되고, 중간에 비어있는 인덱스가 있는 경우 해당 인덱스는 건너뛰고 처리된다.


2.5 Spread(전개연산자)

전개연산자는 배열의 요소나 객체를 나열할 수 있는 연산자로 전개 대상은 반드시 iterable객체여야 한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
  const arr1 = [1,2,3];
  const arr2 = [4,5,6];

  console.log(...arr1);               //result : 1 2 3;
  console.log([...arr1,  ...arr2]);   //result : [1,2,3,4,5,6];

  const obj1 = {1:"one", 2:"two"}
  const obj2 = {3:"three", 4:"four"}

  console.log(...obj1);     
  //result : Uncaught TypeError: Found non-callable @@iterator

  console.log({...obj1, ...obj2});
  //result : {1: 'one', 2: 'two', 3: 'three', 4: 'four'}


2.6 Class

ES6에서 Class 문법이 추가 됐고, 기존의 protoType 기반으로 클래스를 생성하는 것 보다 간단하게 사용이 가능하다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//ES5 - prototype 기반
var Add = function(arg1, arg2) {
  this.arg1 = arg1;
  this.arg2 = arg2;
}
Add.prototype.calc = function() {
  return this.arg1 + "+" + this.arg2 + "=" + (this.arg1 + this.arg2);
}
var num = new Add(5,11);
console.log(num.calc());    //result : 5+11=16

//ES6
class Add {
  constructor(arg1, arg2) {
    this.arg1 = arg1;
    this.arg2 = arg2;
  }
  calc() {
    return this.arg1 + "+" + this.arg2 + "=" + (this.arg1 + this.arg2);
  }
}
let num = new Add(5, 11);
console.log(num.calc());    //result : 5+11=16


2.7 Loop(for/of)

for/of 구조의 반복문으로 Array, Strig, Maps, NodeLists 등의 반복 가능한 데이터 구조르 반복할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//arr loop sample
const cars = ["Sonata", 'K5', 'Avante'];
let text = "";

for(let x of cars){
  text += x + "/";
}

console.log(num);     //result : Sonata/K5/Avante/


//string loop sample
let language = "ES6";
let text = "";

for(let x of language){
  text = x + " ";
}

console.log(text);   //result : E S 6



3. 문자열 관련 문법

3.1 replaceAll()

하나의 문자열을 수정하는 replace와 다르게 일치하는 모든 문자열을 치환하고 새로운 문자열을 반환한다.(기존 문자열은 유지)

1
2
3
4
var str = "abcdeabced";

var str2 = str.replaceAll("a", "A");
//result : str2 -> "AbcedAbced", str -> "abcedabced"


3.2 String padding

문자열의 시작이나 끝을 공백이나 다른 문자열로 채워 원하는 길이의 새로운 문자열을 만들어 낼 수 있다.

1
2
3
4
5
6
var str = "ABC";

str.padStart(5);          //result : "  ABC"
str.padEnd(4);            //rseult : "ABC "
str.padStart(5, "*");     //result : "**ABC"
str.pandEnd(4, "*");      //result : "ABC*"


3.3 trimStart(), trimEnd()

문자열 앞, 뒤 여백을 제거한다.

1
2
3
4
5
6
7
8
9
"String".trimStart();     // "String"
"String ".trimStart();    // "String "
" String".trimStart();    // "String"
" String ".trimStart();   // "String "

"String".trimEnd();       // "String"
"String ".trimEnd();      // "String"
" String".trimEnd();      // " String"
" String ".trimEnd();     // " String"