React ES6 정리(1)

김소희·2025년 11월 3일

let / const - 새로운 변수 선언 방식

ES6에서는 기존 var 키워드의 문제점을 해결하기 위해 letconst가 도입되었다.

var의 문제점

// var는 재선언이 가능하다 (문제가 될 수 있음)
var total = 200;
console.log(total); // 200

var total = 500; // 재선언 가능 (위험!)
console.log(total); // 500

let - 재할당 가능

// let은 재할당은 가능하지만 재선언은 불가능하다
let total = 200;
console.log(total); // 200

total = 500; // 재할당 가능
console.log(total); // 500

// let total = 300; // 에러! 재선언 불가능

const - 재할당 불가

// const는 재할당과 재선언 모두 불가능하다
const total = 200;
console.log(total); // 200

// total = 500; // 에러! 재할당 불가능
// const total = 300; // 에러! 재선언 불가능

사용 권장사항:

  • 기본적으로 const 사용
  • 재할당이 필요한 경우에만 let 사용
  • var는 사용하지 않는다

화살표 함수 (Arrow Function)

화살표 함수는 함수를 더욱 간결하게 표현할 수 있는 ES6의 문법이다.

기본 문법

// 기존 익명 함수
let foo = function() {
    console.log("foo");
}
foo();

// ES6 화살표 함수
let bar = () => console.log("bar 함수");
bar();

매개변수가 1개인 경우

// 매개변수가 1개일 때는 괄호 생략 가능
let foo2 = x => x;
let data = foo2(100);
console.log("data", data); // 100

// 예제 2
let hello = val => "hello " + val;
const value = hello("world");
console.log(value); // "hello world"

매개변수가 2개 이상인 경우

// 매개변수가 2개 이상이면 괄호 필수
let foo3 = (x, y) => x + y;
const value2 = foo3(10, 30);
console.log(value2); // 40

실행 블럭이 필요한 경우

// 논리가 복잡하면 중괄호 사용 (지역변수, if문 등)
let foo4 = (a, b) => {
    let c = 100;
    return a + b + c;
}

const value3 = foo4(10, 20);
console.log(value3); // 130

JavaScript 일급 함수 (First-Class Function)

JavaScript에서 함수는 일급 객체(일급 함수)이다. 일급 함수란 다음의 조건을 만족하는 함수를 말한다.

함수를 변수에 할당

const add = function() {
    return 10 + 20;
}
add(); // 함수 호출

함수를 객체에 저장

// 객체에 함수 저장
const call = { add };

// 배열에 함수 저장
const calls = [];
calls.push(add);

참고: 배열 사용 시 push(), pop() 메서드를 사용하는 것이 좋은 코드이다 (Stack 구조 - LIFO)

함수를 매개변수로 전달

function hello() {
    console.log("my call");
}

function greeting(message, name) {
    message(); // hello() 함수 호출
}

greeting(hello, "script");

함수를 리턴

// 함수가 함수를 리턴
function world() {
    return () => { 
        console.log("function return"); 
    }
}

Template Literal (템플릿 리터럴)

백틱(`)과 ${}를 결합하여 문자열을 더욱 편리하게 작성한다.

기본 사용법

// 기존 방식
const lang = "javascript";
const expression = "I love " + lang + "!!!";
console.log(expression);

// Template Literal 방식
const expression2 = `I love ${lang}!!!`;
console.log(expression2);

표현식 안에서 함수 사용

// 문자열 메서드 체이닝 가능
const lang = "javascript";
const expression = `I love ${lang.split('').reverse().join('')}!!!`;
console.log(expression); // "I love tpircsavaj!!!"

// 배열 조작
const arr = ["바람", "비", "물"];
console.log(arr.join('-')); // "바람-비-물"

객체 속성 참조

const user4 = {
    name: "순신",
    age: 30
};

const userData = `사랑하는 ${user4.name}는 이제 ${user4.age}살 입니다`;
console.log(userData); // "사랑하는 순신는 이제 30살 입니다"

Enhanced Object Literal (향상된 객체 리터럴)

객체 표기를 더욱 간결하게 작성할 수 있는 방법이다.

속성 축약 표현

// 키와 값이 같을 때 생략 가능
const language = "java";
const dataObj2 = { language }; // { language: "java" }

메서드 축약 표현

// 기존 방식
const dataObj3 = {
    coding: function() {
        console.log("hello coding");
    }
};
dataObj3.coding();

// 축약 표현
const dataObj4 = {
    coding() { // function 키워드 생략 가능
        console.log("hello coding");
    }
};
dataObj4.coding();

Spread Operator (펼침 연산자)

... 연산자를 사용하여 배열이나 객체를 복제하거나 합칠 수 있다.

객체 복제

const obj = {
    a: 10,
    b: 20
};

let newObj = {...obj}; // 복제
console.log(newObj); // { a: 10, b: 20 }

배열 복제

const arr = [1, 2, 3];
let newArr = [...arr]; // 복제
console.log(newArr); // [1, 2, 3]

배열 합치기

const arr3 = [1, 2, 3];
const arr4 = [4, 5, 6];

const combineArray = [...arr3, ...arr4];
console.log(combineArray); // [1, 2, 3, 4, 5, 6]

// 중간에 요소 추가도 가능
const arr5 = [1, 2, 3];
const newArray = [10, ...arr5, 40, 50];
console.log(newArray); // [10, 1, 2, 3, 40, 50]

객체 합치기 및 속성 추가

const obj3 = { name: "길동" };
const obj4 = { age: 25 };
const combineObj = {...obj3, ...obj4};
console.log(combineObj); // { name: "길동", age: 25 }

// 속성 추가
const person = { name: "길동", age: 25 };
const updatePerson = {...person, city: "Seoul"};
console.log(updatePerson); // { name: "길동", age: 25, city: "Seoul" }

속성 덮어쓰기 (Overwrite)

let user = {
    name: "소희",
    age: 30,
    city: "busan"
};

// age 속성 변경 및 hobby 추가
let user2 = {...user, age: 10, hobby: "read book"};
console.log(user2);
// { name: "소희", age: 10, city: "busan", hobby: "read book" }

구조 분해 할당 (Destructuring Assignment)

배열이나 객체의 값을 간편하게 변수로 추출할 수 있다.

객체 구조 분해

const obj = { a: 10, b: 20, c: 30 };

const {a, b, c} = obj;
console.log(a); // 10
console.log(b); // 20
console.log(c); // 30

// 실무 예제
const smith = {
    lang: "js",
    position: "front",
    area: "gang_nam",
    hobby: "baseball",
    age: "90"
};

const {lang, position, area, hobby, age} = smith;
console.log(lang); // "js"
console.log(position); // "front"

배열 구조 분해

const numbers = [11, 22, 33];
const [first, second, third] = numbers;
console.log(first); // 11

// 특정 요소만 선택
const number3 = [1, 2, 3, 4, 5];
const [,, third3, fourth3] = number3;
console.log(third3); // 3
console.log(fourth3); // 4

Default Parameter (기본값 매개변수)

함수의 매개변수에 기본값을 설정할 수 있다.

기존 방식 (OR 연산자 사용)

function printPersonData(height, weight, age) {
    let he = height || 100;
    let we = weight || 60;
    let a = age || 50;
    
    console.log(he, we, a);
}

printPersonData(10, 20, 30); // 10, 20, 30
printPersonData(); // 100, 60, 50

ES6 방식 (기본값 설정)

function printPersonData2(height2 = 100, weight2 = 60, age2 = 50) {
    console.log(height2, weight2, age2);
}

printPersonData2(10, 20, 30); // 10, 20, 30
printPersonData2(); // 100, 60, 50

다양한 타입의 기본값 설정

function call(param = 1, param1 = {}, param2 = "korean") {
    console.log(param, param1, param2);
}

call(30, {name: "길동"}, "american"); // 30, {name: "길동"}, "american"
call(); // 1, {}, "korean"

이어서 -> React ES6 정리(2)

profile
개발자 소희의 노트

0개의 댓글