JavaScript ES6 문법 정리
1. ECMAScript(ECMA) 문법이란?
- ECMAScript(ECMA-262): 자바스크립트의 핵심 문법과 규칙을 정의한 표준 사양.
- JavaScript: ECMAScript 표준을 기반으로 만들어진 프로그래밍 언어로, 웹 API 등을 포함.
배경
- 1990년대 초반:
- Netscape: JavaScript 개발
- MS: JScript 개발
→ 브라우저별 다른 문법으로 인해 호환성 문제 발생.
- 표준화 필요성 대두 → Ecma International에서 표준 제정.
- 표준 명칭: ECMA-262 (언어 명칭: ECMAScript)
2. ES6(2015) 주요 문법
2.1 변수 선언: let과 const
let: 재할당 가능, 블록 스코프
const: 재할당 불가, 블록 스코프 (상수)
- 객체/배열은
const여도 내부 값 변경 가능, 재할당만 불가능.
let name = '을지문덕';
name = '이순신'; // 가능
const PI = 3.141592;
// PI = 3.14; // ❌ 오류
const person = { name: '홍길동' };
person.name = '김철수'; // 가능
// person = { name: '박영희' }; // ❌ 재할당 불가
2.2 화살표 함수 (Arrow Function)
function 대신 => 사용.
this가 상위 스코프를 유지.
- 매개변수 1개면
() 생략 가능, return만 있으면 {}와 return 생략 가능.
// ES5
var add = function(a, b) {
return a + b;
};
// ES6
const add = (a, b) => a + b;
// 매개변수 1개
const double = a => a * 2;
// 블록문
const square = x => {
return x * x;
};
---
const obj = {
name: '홍길동',
normalFunc: function() {
console.log(this.name);
},
arrowFunc: () => {
console.log(this.name);
}
};
obj.normalFunc(); // 홍길동
obj.arrowFunc(); // undefined
---
function Person(name) {
this.name = name;
setTimeout(function() {
console.log(this.name);
}, 1000);
}
new Person('이순신');
// undefined (setTimeout 안의 this는 전역)
---
function Person(name) {
this.name = name;
setTimeout(() => {
console.log(this.name);
}, 1000);
}
new Person('이순신');
// 1초 후 → "이순신"
2.3 템플릿 리터럴 (Template Literals)
- 백틱(
`)을 사용해 문자열 안에 ${변수}로 값 삽입 가능.
- 여러 줄 문자열 작성 가능.
const name = '홍길동';
const age = 30;
// ES5
console.log('이름: ' + name + ', 나이: ' + age);
// ES6
console.log(`이름: ${name}, 나이: ${age}`);
console.log(`여러 줄
문자열 작성 가능`);
2.4 구조 분해 할당 (Destructuring Assignment)
// 객체
const person = { name: '홍길동', age: 30 };
const { name, age } = person;
// 배열
const colors = ['red', 'green', 'blue'];
const [firstColor, secondColor] = colors;
2.5 전개 연산자 (Spread) & 나머지 매개변수 (Rest)
- Spread: 배열/객체의 값을 펼쳐서 복사·합치기.
- Rest: 나머지 인자들을 배열로 받기.
// Spread
const arr1 = [1, 2];
const arr2 = [3, 4];
const combined = [...arr1, ...arr2]; // [1, 2, 3, 4]
// 객체 병합
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const merged = { ...obj1, ...obj2 }; // {a:1,b:2,c:3,d:4}
// Rest
function sum(...nums) {
return nums.reduce((acc, n) => acc + n, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
2.6 클래스 (Class)
- 프로토타입 기반 상속을 더 직관적으로 사용 가능.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayHello() {
console.log(`안녕하세요, 저는 ${this.name}입니다.`);
}
}
class Student extends Person {
constructor(name, grade) {
super(name);
this.grade = grade;
}
}
const person1 = new Person('홍길동', 30);
person1.sayHello();
2.7 모듈 (Module)
- 코드 분리 및 재사용 가능.
export / import 사용.
// math.js
export const add = (a, b) => a + b;
export default function hello() { console.log("Hello"); }
// main.js
import hello, { add } from './math.js';
hello();
console.log(add(5, 3));
2.8 기본 매개변수 (Default Parameters)
function greet(name = '고객') {
console.log(`안녕하세요, ${name}님.`);
}
greet(); // 안녕하세요, 고객님.
2.9 프로미스 (Promise)
- 비동기 작업 처리 객체.
- 성공(resolve) / 실패(reject) 상태 관리.
const p = new Promise((resolve, reject) => {
setTimeout(() => resolve("완료"), 1000);
});
p.then(result => console.log(result))
.catch(error => console.error(error));
2.10 객체 리터럴 개선 (Object Literal Shorthand)
- 변수명과 속성명이 같으면 생략 가능.
- 메서드 정의 시
function 키워드 생략.
const x = 10, y = 20;
const obj = { x, y, greet() { console.log("hi"); } };
2.11 Symbol
const id = Symbol("id");
2.12 이터레이터 & for...of
for...of를 사용해 반복 가능한 객체 순회.
const arr = [1, 2, 3];
for (let value of arr) {
console.log(value);
}
2.13 Map & Set
- Set: 중복 없는 값 저장.
- Map: 키-값 쌍 저장.
// Set
const set = new Set([1, 2, 2, 3]); // {1,2,3}
// Map
const map = new Map();
map.set("a", 1);
console.log(map.get("a")); // 1