All Articles

[Node.js] Javascript ES6 & ES11 문법 정리

안녕하세요!

이번 포스팅 에서는 Javascript 버전에 새로 추가된 ES6ES11 문법에 대해 소개 해 드리고자 합니다.
Javascript 뿐만 아니라 React, Vue, Node.js 에서도 유용 하게 쓰는 문법 이므로 숙지해 두면 좋을 것 같습니다!😄


⭐ ES6 문법.

  • 아래 예제를 통해 Javascript ES6 버전의 문법을 소개해 드리겠습니다.
  • AS-IS 코드와 TO-BE 코드를 비교 해서 살펴 보신 다면 ES6 문법이 적용된 코드가 훨씬 간결 하고 가독성이 좋아진 것을 느끼실 수 있을 것 입니다!👍🏻

1. Default Parameters

  • 함수에 파라미터 인자가 전달 되지 않았을 경우 초기 값을 지정 하여 나타내 주는 기능 입니다.
  • 예제 코드 설명

    • printMessage이라는 함수에 message라는 인자가 전달되었을 때 값이 있으면 console에 출력하고, 값이 null이면 default message라고 나타내는 함수 입니다.
  • AS-IS
function printMessage(message) {
    if(message == null){
        message = 'default message';
    }
    console.log(message);
}

printMessage('hello');
printMessage();
  • TO-BE

    • message 인자에 default message라는 초기값을 할당해 준 상태에서 함수를 호출하게 되면 위의 코드와 동일한 결과로 나타납니다.
function printMessage(message= 'default message') {
    console.log(message);
}

printMessage('hello');
printMessage();

2. Shorthand Property Names

  • Objectproperty가 변수명과 동일한 경우, 변수명을 그대로 사용할 수 있는 기능 입니다.
  • 예제 코드 설명

    • code1에서는 Object에 변수명을 직접 할당해 주었고, code2에서는 이미 선언된 변수명을 불러옵니다.
  • AS-IS
{
    const code1 = {
        name: 'sangeun',
        age: '18'
    };
   
    const name = 'sangeun';
    const age = '18';

    const code2 = {
        name: name,
        age: age
    };
    console.log(code1, code2);
}
  • TO-BE

    • Property가 변수명과 동일 한 name, age 이므로 단축 구문을 사용 해서 아래와 같이 표현할 수 있습니다.
{
    const name = 'sangeun';
    const age = '18';
    

    const code3 = {
        name,
        age
    };
    console.log(code3);
}

3. Spread Syntax

  • ObjectArray의 얕은 복사에 사용 하는 기능 입니다.
  • 예제 코드 설명

    • Object로 나타낸 obj1obj2를 배열로 처리 하여 새로운 배열로 나타낸 예제 입니다.
    • ...array를 사용하여 배열을 copy하고, 얕은 복사를 통해 copy한 배열에 새로운 object를 추가할 수 있습니다.
  • TO-BE
{
    const obj1 = {key: 'key1'};
    const obj2 = {key: 'key2'};
    const array = [obj1, obj2];

    // array copy
    const arrayCopy = [...array];
    console.log(array, arrayCopy);

    const arrayCopy2 = [...array, {key: 'key3'}];
    obj1.key = 'newKey';
    console.log(array, arrayCopy, arrayCopy2);

    //object copy
    const obj3 = {...obj1};
    console.log(obj3);
}
  • 결과
[ { key: 'key1' }, { key: 'key2' } ] [ { key: 'key1' }, { key: 'key2' } ]
[ { key: 'newKey' }, { key: 'key2' } ] [ { key: 'newKey' }, { key: 'key2' } ] [ { key: 'newKey' }, { key: 'key2' }, { key: 'key3' } ]
{ key: 'newKey' }

4. Template Literal

  • 문자열에 특정 변수의 값을 함께 사용할 때 유용한 기능 입니다.
  • 예제 코드 설명

    • ${}를 사용하여 특정 변수를 대입할 수 있고, 문자열을 연결하기 위해 일일이 + 하지 않아도 됩니다.
    • 또한 대신 백틱(back-tick)이라는 기호 ` 를 사용해야 합니다.
  • AS-IS
{
    const weather = '☀️';
    const temperature = '21도';

    console.log(
        'Today weather is ' + weather + ' and temperater is ' + temperature + '.'
    )
}
  • TO-BE
{
    const weather = '☀️';
    const temperature = '21도';
   
    console.log(
        `Today weather is ${weather} and temperater is ${temperature}.`
    )
}

5. Ternary Operator

  • 조건부 삼항 연산자는 Javascript에서 3개의 피연산자를 취할 수 있는 유일한 연산자 입니다. 보통 if 문의 단축 형태로 쓰입니다.
  • 예제 코드 설명

    • isDog이 true/false 인에 따라 component 변수를 출력 합니다.
  • AS-IS
{
    const isDog = true;
    
    {
        let component;
        if(isDog){
            component = '🐶';
        }else{
            component = '🐼';
        }
        console.log(component);
    }
}
  • TO-BE
{
    const isDog = true;
    
    {
        const component = isDog ? '🐶':'🐼';
        console.log(component);
    }
}

️🌟 ES11 문법.

1. Optional Chaining

  • 프로퍼티가 없는 중첩 객체를 에러 없이 안전하게 사용할 수 있는 기능 입니다.
  • 예제 코드 설명

    • person1, person2라는 Object가 선언 되어 있습니다. 여기에 printManager라는 함수를 호출 하기 위해서 person 이라는 파라미터를 사용하게 되는데요.
    • person1 에서는 person.job.manager.name 파라미터가 있으므로 호출을 할 수 있지만, person2에는 해당 파라미터가 없으므로 에러를 출력하게 됩니다.
  • AS-IS
{
    const person1 = {
        name: 'Sangeun',
        job: {
            title: 'S/W Engineer',
            manager: {
                name: 'Bob'
            },
        },
    };

    const person2 = {
        name: 'Bob'
    }
    
    {
        function printManager(person) {
            console.log(person.job.manager.name);
        }
        printManager(person1);
        printManager(person2);
    }
}
  • TO-BE

    • ES11 버전에 추가된 ?. 연산자를 사용하게 된다면 person2에 해당 파라미터가 없더라도 에러를 출력하지 않고 undefined를 출력하게 됩니다.
{
    const person1 = {
        name: 'Sangeun',
        job: {
            title: 'S/W Engineer',
            manager: {
                name: 'Bob'
            },
        },
    };

    const person2 = {
        name: 'Bob'
    }

    {
        function printManager(person) {
            console.log(person.job?.manager?.name);
        }
        printManager(person1);
        printManager(person2);
    }
}

2. Nullish Coalescing Operator

  • ?? 연산자를 사용 하여 왼쪽 피연산자가 null이나 undefined일 때 오른쪽 피연산자를 return 합니다. 반대의 경우는 왼쪽 피연산자가 return 됩니다.
  • 예제 코드 설명

    • false가 출력되는 경우는 false, '', 0, null, undefiend 입니다.
    • 그런데 원하는 값이 실제로 false, '', 0, null, undefiend 일수도 있습니다. 이런 경우에 유용 하게 사용할 수 있는 기능 입니다.
  • AS-IS
{
    {
        const name = 'Alice';
        const userName = name || 'Guest';
        console.log(userName);
    }

    {
        const name = null;
        const userName = name || 'Guest';
        console.log(userName);

        const num = 0;
        const message = num || 'undefined';
        console.log(message);
    }
}
  • TO-BE

    • ?? 연산자를 사용하여 왼쪽 피연산자가 ''이거나 0일 때 오른쪽 피연산자를 return 합니다.
{
    {
        const name = '';
        const userName = name ?? 'Guest';
        console.log(userName);

        const num = 0;
        const message = num ?? 'undefined';
        console.log(message);
    }
}

오늘 준비한 내용은 여기까지 입니다.
이번 포스팅이 도움이 되셨거나 궁금한 점이 있으시다면 언제든지 댓글을 달아주세요!🙋🏻‍♀️✨