Chapter 4. ES6와 프로젝트 파일 구조의 이해(1)

Arin·2025년 12월 26일

UMC 8기 - Node.js

목록 보기
5/11

ES

ES (Ecma Script) : ECMA international에서 정한 자바스크립트의 표준, 규격

ES는 버전이 계속 업데이트되어 ES5, ES6 등등의 버전이 있다.

ES6이후로도 업데이트가 되고있지만, ES6가 가장 큰 변화를 가져온 버전이기 때문에 중요하게 다뤄진다.

ES6

ES6의 주요 변화 및 특징

  1. letconst도입

    var의 단점을 보완하기 위해 let과 const를 도입했다.

    • var (문제점 3가지)
      • 스코프 범위가 function
        if(true){
        	var a =10;
        }
        console.log(a); // 10 (블록 밖에서도 접근이 가능하여 문제 발생 가능) 
      • 중복 선언 가능
        var name = "cindy";
        var name = "chill"; // 중복 선언 가능하여 문제 발생 가능 
      • Hoisting이 가능 Hoisting이란, 인터프리터가 코드를 실행하기 전에 함수, 변수, 클래스 또는 임포트(import)의 선언문을 해당 범위의 맨 위로 끌어올리는 것처럼 보이는 현상이다. 그래서 아래 코드처럼 아직 선언되지도 않은 변수를 사용할 수 있는 현상이 발생한다.
        console.log(name); // undefined(->원래 오류가 나야 정상인데, 변수를 인식하고있음) 
        var name = "cindy"
        console.log(name); // cindy
    • let
      • 스코프 범위가 중괄호이다(for, if, function)
        if (true) {
          let b = 20;
        }
        console.log(b); // 오류 발생 (b는 블록 안에서만 유효)
      • 재할당 가능
      • 중복 선언 불가능
    • const
      • 스코프 범위가 중괄호이다(for, if, function)
      • 재할당 불가능
      • 중복 선언 불가능
  2. 화살표 함수 (Arrow Functions)가 추가됨
    표기:

    화살표 함수는 동적으로 this가 바인딩 되지 않고 고정되어서 버그가 줄어든다.

    참고) this의 동적 vs 정적

    • 동적인 this

      예시 ) 일반함수

      const person = {
        name: "Alice",
        greet: function() {
          function innerFunc() {
            console.log(this.name); // this == window
          }
          innerFunc(); // 일반함수로 호출됨 
        }
      };
      
      person.greet(); // undefined 또는 에러(window.name이 없음)
    • 정적인 this

      예시) 화살표 함수

      const person = {
        name: "Bob",
        greet: function() {
          const arrowFunc = () => {
            console.log(this.name); // this == person객체
          };
          arrowFunc(); // 화살표함수로 호출됨
        }
      };
      
      person.greet(); // Bob
  3. 클래스 문법 제공
    이전에는 prototype 기반이었지만 이젠 클래스 기반으로 더 직관적인 객체 생성 가능 !

    class Animal {
      constructor(name) {
        this.name = name;
      }
    
      speak() {
        console.log(`${this.name}이(가) 소리를 낸다.`);
      }
    }
    
    const dog = new Animal('강아지');
    dog.speak(); // 강아지가 소리를 낸다.
  4. 템플릿 리터럴 (백틱)

    이전에는 문자열을 이어붙일 때 +를 썼지만 이젠 백틱(```)과 ${}` 문법 사용 가능

    const name = '철수';
    const age = 20;
    
    const message = `안녕하세요, 제 이름은 ${name}이고 나이는 ${age}살입니다.`;
    console.log(message);
  5. 구조 분해 할당 (Destructuring)
    배열이나 객체에서 필요한 값을 변수로 꺼내기 쉽게 해준다.

    // 배열
    const [x,y] = [1,2];
    console.log(x); // 1
    
    // 객체
    const person = {name: "아린", age: 25};
    const { name, age } = person;
    console.log(name); // 아린
  6. 스프레드 연산자
    배열/객체를 복사하거나 병합할 때 사용한다.

    함수 인자처럼 펼쳐 쓸 수도 있다.

     const arr1 = [1,2];
      const arr2 = [...arr1, 3, 4];
      console.log(arr2); // [1,2,3,4]
    
      const user = {name:"아린"};
      const newUser = {...user, age:25};
      console.log(newUser); // { name: '아린', age: 25 }
  7. 기본 매개변수
    함수에 인자를 안 넣으면 사용되는 기본 값 설정 가능

    function greet(name = "손님") {
        console.log(`안녕하세요, ${name}님!`);
    }
    
    greet(); // 안녕하세요, **손님**님!
    greet("아린"); // 안녕하세요, 아린님!
  8. Promise (비동기 처리)
    then, catch로 콜백 지옥을 피하게 도와주는 기능이다.

    const fetchData = new Promise((resolve, reject) => {
      const success = true;
      if (success) {
        resolve("데이터 성공!");
      } else {
        reject("에러 발생!");
      }
    });
    
    fetchData.then(data => console.log(data)).catch(err => console.error(err));
    		```
      
  9. 모듈(import, export)
    파일을 분리해서 코드를 재사용하기 쉽게 만들었다

    // math.js
    export const add = (a, b) => a + b;
    
    // app.js
    import { add } from './math.js';
    console.log(add(3, 4)); // 7
  10. Symbol
    고유한 값을 만들기 위한 유일한 키

    → 다른 키와 절대 충돌 안나게 할 때 사용

    const id = Symbol('id');
    const user = {[id]:123};
    
    console.log(user[id]); // 123
  11. Set / Map

    • set: 중복없는 값들의 모음
    • Map: 키-값 쌍을 저장하는 자료구조
    const set = new Set([1, 2, 2, 3]);
    console.log(set); // Set { 1, 2, 3 }
    
    const map = new Map();
    map.set('name', '아린');
    map.set('age', 25);
    console.log(map.get('name')); // 아린

ES6를 중요시 하는 이유

ES6는 JavaScript 코드의 효율성, 가독성, 유지보수성을 높여주는 핵심적인 변화를 가져왔기 때문에 현대 JavaScript 개발의 표준이라고 할 수 있다.

ES Module

ES Module이란 import와 export를 통해 모듈을 관리할 수 있게 해주는 시스템이다.

<사용법>

  1. package.json"type":"module" 설정
{
	"type": "module"
}
  1. .mjs 확장자 , import 구문 사용

    a. 내보내기

    // math.js
    export const add = (a, b) => a + b;
    export const subtract = (a, b) => a - b;

    b. 가져오기

    // app.js
    import { add, subtract } from './math.js';
    
    console.log(add(2, 3)); // 5
    console.log(subtract(5, 3)); // 2
profile
헤맨만큼 내 땅

0개의 댓글