ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Javascript ES6 에 추가된 기능 간단 정리
    Knowledge/javascript 2019. 11. 15. 23:01
    반응형

    ES6에서 추가된 기능 ( String Literal, 객체 비구조화 ( Object Destructuring ), 객체 리터럴 ( Object Literal ), for .. of, Spread Operator, Rest Parameter, Arrow Function, Default Params, includes, let & const, import & export, Classes , Trailing Commas, Map & Set, Async & Await ) 에 대해 공부하고 최대한 간단히 볼 수 있도록 짧게 정리했습니다.

     

    예제 코드에서 주석처리한 부분은 출력 결과고 예제 실습은 https://es6console.com/ 에서 진행할 수 있습니다

     

    - String Literal

     

    ES6의 String Literal을 활용하면 문자열을 좀 더 직관적으로 결합할 수 있다.

    ( 여기서 사용되는 ` 은 Tab키 위에 있는 ` 다. 작은 따옴표 아님 )

     

    - 예제 코드

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    const val1 = 'my string';
    const val2 = 'my string2';
     
    // es5
     
    const conVal = val1 + ', '+ val2;
     
    console.log(conVal);
    // my string, my string2
     
    // es6
     
    const litVal = `${val1}, ${val2}`
     
    console.log(litVal);
    // my string, my string2

     

     

    - 객체 비구조화 ( Object Destructuring )

     

    객체에 들어있는 값들 각각을 꺼내 쓸 수 있다.

     

    - 예제 코드

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    const address = {
        country: 'South Korea',
        city : 'Seoul',
        street: 'Gangnam',
        str_num: 141,
        postcode:'00510',
      }
      
      const { country, city, street, str_num, postcode } = address;
      
      console.log(country);
      // South Korea
      console.log(city);
      // Seoul
      console.log(street);
      // Gangnam
      console.log(str_num);
      // 141
      console.log(postcode);
      // 00510

     

    - 객체 리터럴 ( Object Literal )

     

    ES6에선 객체 프로퍼티 이름이 로컬 변수 이름과 같으면 콜론과 값 없이 작성해도 된다.

    값을 직접 명시해주는 경우와 함께 사용할 수도 있다

     

    - 예제 코드

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    function getAddress(country, city, street) {
        const myAddress  = {
          country, 
          city, 
          street,
          str_num:888,
          postcode: '9999'
        };
        console.log(myAddress);
        // { country: 'Korea',
        //   city: 'Seoul',
        //   street: 'Euncheon',
        //   str_num: 888,
        //   postcode: '9999' }
      }
      
      getAddress('Korea','Seoul','Euncheon');

     

    - for .. of

     

    es5 에서도 for .. in 이나 forEach 처럼 반복문을 좀 더 간편하게 쓰려는 시도는 있었지만 효율적이지 않았다

    ( 지금은 둘 모두 사용을 권장하지 않는다. ) 

     

    for.. of는 이런 아쉬움을 덜어내 줄 수 있도록 ES6에 추가된 효율적인 반복문이다

     

    - 예제코드

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    let years = [20012010,20152018];
    const str = 'Test';
     
    // es5
     
    // for(변수 in 배열) 을 사용하면 키 값이 출력된다 ( 사용 권장하지 않음 )
     
    for(let year in years){
        console.log(year);
        // 0, 1, 2, 3
    }
     
    // forEach의 경우 출력은 똑같이 되지만 가독성이 떨어지고 
    // 내부에서 break 문 등을 사용할 수 없다. ( 사용 권장하지 않음 )
     
    years.forEach((year) => {
        console.log(year);
        // 2001, 2010, 2015, 2018
    })
     
    // es 6
     
    for(let year of years){
        console.log(year);
        // 2001
        if(year == 2001){
            break;
        }
        // 내부에서 break 문 사용 가능
    }
     
    for(let char of str){
        console.log(char);
        // T, e, s, t
    }
     

     

    - Spread Operator

     

    배열이나 객체, 문자열을 ...과 함께 사용하면 배열, 객체, 문자열을 결합하기가 매우 수월해졌습니다.

     

    - 예제코드

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    // Spread Operateor
     
    let years = [20012010,20152018];
    let yearsCp = [2000...years, 2020];
     
    console.log(yearsCp);
    // [ 2000, 2001, 2010, 2015, 2018, 2020 ]
     
    let koreanHistory = {
        liberate : 1945,
        6251950
    };
     
    let history = {
        worldWar1: 1914,
        worldWar2: 1945,
        ... koreanHistory
    }
     
    console.log(history);
    // { '625': 1950, worldWar1: 1914, worldWar2: 1945, liberate: 1945 }

     

    - Rest Parameter

     

    ... 을 함수의 인자에 사용하면 인자를 배열로 받을 수 있다

     

    - 예제코드

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    function printYears(years) {
        console.log(years);
        // 2000
    }
     
    printYears(20002001201020152018);
     
    function printYearsWithRestParameter(...years){
        console.log(years);
        // [ 2000, 2001, 2010, 2015, 2018 ]
    }
     
    printYearsWithRestParameter(20002001201020152018);

     

    - Arrow Function

    Arrow Function을 활용하면 함수 표현을 기존의 function 표현보다 짧은 구문으로 표현할 수 있다.

     

    - 예제 코드

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    const years = [
        {
            year: 2000,
            data: '크리스마스',
        },
        {
            year: 2001,
            data: '로스트메모리즈',
        },
        {
            year: 2002,
            data: '월드컵',
        },
        {
            year: 2015,
            data: '리액트네이티브',
        },
        {
            year: 2019,
            data: '올해',
        },
    ];
     
    const result = years.filter(function(data){
        return data.year > 2008;
    });
     
    console.log(result);
    // [ { year: 2015, data: '리액트네이티브' }, { year: 2019, data: '올해' } ]
     
    const arrowReulst = years.filter((data) => data.year > 2008);
     
    console.log(arrowReulst);
    // [ { year: 2015, data: '리액트네이티브' }, { year: 2019, data: '올해' } ]

     

    - Default Params

     

    es6에선 함수의 기본 파라미터를 세팅해줄 수 있다.

     

    - 예제코드

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    const defaultValue = [
        {
            year: 2000,
            data: '크리스마스',
        },
        {
            year: 2001,
            data: '로스트메모리즈',
        },
        {
            year: 2002,
            data: '월드컵',
        },
        {
            year: 2015,
            data: '리액트네이티브',
        },
        {
            year: 2019,
            data: '올해',
        },
    ];
     
    function printYears(years = defaultValue){
        // default Value를 default Parameter로 설정해줄 수 있다
        console.log(years)
    }
     
    console.log('인자 없이 호출')
    printYears();
     
    // 인자 없이 호출
    // [ { year: 2000, data: '크리스마스' },
    //   { year: 2001, data: '로스트메모리즈' },
    //   { year: 2002, data: '월드컵' },
    //   { year: 2015, data: '리액트네이티브' },
    //   { year: 2019, data: '올해' } ]
     
    console.log('인자 넣고 호출')
    printYears({
        year:1864,
        data:'크리스마스',
    });
     
    // 인자 넣고 호출
    // { year: 1864, data: '크리스마스' }

    - includes

     

    es5에서 배열에 특정 값이 있는지 알고싶으면 indexOf를 활용해 -1 값이 있는지를 봐야했다.

    es6에선 includes를 활용하면 배열에 특정값이 있는지를 깔끔하게 확인할 수 있다.

     

    - 예제 코드

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    let years = [2001,2010,20152018];
    const fruits = ['apple','banana','potato'];
     
    // es5
     
    console.log(years.indexOf(2014!== -1);
    // false
    console.log(fruits.indexOf('apple'!== -1);
    // true
     
    // es6
     
    console.log(fruits.includes('appl'));
    // false
    console.log(fruits.includes('apple'));
    // true

     

    - let & const

     

    es5에선 변수를 var로만 선언할 수 있었다. 그러나 es6에서 let과 const가 추가되었다.

    let과 const를 활용하면 예상하지 못한 오류가 발생하는 걸 막을 수 있다. 이를 사용하길 권장한다.

    ( var, let, const 차이에 관한 상세한 포스팅은 아래 참고)

     

    ES6, Hoisting으로 다시 보는 let, const

    Javascript Hoisting에 대해 다시 살펴보던 도중, 예전에 공부할땐 var를 대상으로 공부했으니 깨닫지 못했는데 이번에 let, const…

    junhobaik.github.io

     

    - 예제 코드

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    // var 과 let의 차이
     
    if(true) {
        var varId = 'test';
        // var로 선언
    }
     
    console.log(varId);
    // test
    // scope가 다른데도 varId가 출력된다
     
    if(true) {
        let hoistingId = 'test';
        // let으로 선언
    }
     
    // error로 실행 불가
    // scopre가 다르기 때문에 당연히 에러 발생
     
    // let과 const의 차이
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    // let과 const 차이
     
    let letId = 'testBefore';
    letId = 'testAfter';
     
    console.log(letId);
    // testAfter
     
    const constId = 'testBefore';
    //constId = 'testAfter';
    // const로 선언된 변수를 재할당 하려하면 error 발생으로 실행불가
    // 즉 const 로 선언된 변수의 값은 변하지 않는다.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    // const로 객체와 배열을 선언했을 때 예외사항
     
    const fruit = {};
    // fruit = {test : 'apple'};
    // fruit 값을 직접 바꾸려 하면 에러가 발생하지만
     
    fruit.first = 'apple';
    console.log(fruit);
    // { first: 'apple' }
     
    // 위와 같은 방식으로 객체 내부의 값을 바꾸는 것은 가능하다.
     
    const numbers = [0,1,2];
    numbers[0= 5;
    console.log(numbers);
    // [ 5, 1, 2 ] 
    // 배열도 객체와 마찬가지다

    - import & export

     

    import와 export를 활용하면 다른 파일에서 사용한 원시값, 객체, 배열, 함수 등을 가져와서 쓸 수 있다.

     

    - 예제 코드

    1
    2
    3
    4
     
    export const fruits = ['apple','banana','potato'];
    export const test = 'test입니다';
    1
    2
    3
    4
    5
     
    import { fruits, test } from './export.js';
    console.log(fruits, test);
    // [ 'apple', 'banana', 'potato' ] 'test입니다'

     

    - Classes

     

    es5에서 어떤 함수를 Class처럼 쓰려면 함수를 Class처럼 만들고 prototype을 활용해야 했지만

    es6부터는 객체지향형 프로그래밍 언어들이 지원하던 Class를 javascript에서도 사용할 수 있게 되었다.

     

    - 예제 코드

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    //es5
     
    function Animal() {
        this.type = 'chosic';
        this.tail = false;
    }
     
    Animal.prototype.setType = function (type) {
        this.type = type;
    }
     
    Animal.prototype.getType = function () {
        return this.type;
    }
     
    // es6
     
    class Ani {
        constructor(type,tail){
            // 생성자 지원
            this.type = type;
            this.tail = tail;
        }
     
        cry(value = 'Woof Woof'){
            // 메소드 지원
            console.log(value);
        }
     
        static instance(){
            // static 함수도 지원
            console.log('instance!!');
        }
    }
     
    let dog = new Ani('Dog',true);
    console.log(dog);
    // Ani { type: 'Dog', tail: true }
     
    dog.cry('woof');
    // woof
     
    Ani.instance();
    // instance!!
     
    // 상속도 지원
    class Cat extends Ani{
        constructor(type,tail,color){
            super(type,tail);
            this.color = color;
        }
     
        cry(value = 'Meow Meow'){
            // 메소드 오버라이딩도 지원
            console.log(value);
        }
    }
     
    let cat = new Cat('Cat'true'yellow');
    console.log(cat);
    // Cat { type: 'Cat', tail: true, color: 'yellow' }
    // Meow Meow

     

    - Trailing Commas

     

    es6부터는 trailing comma를 지원하기 때문에 객체나 배열의 마지막 값 뒤에 ,을 붙여도 된다

    ( trailing comma는 데이터가 늘어날 경우를 대비해서 사용한다 )

     

    - 예제 코드

    1
    2
    3
    4
    5
    6
    7
    const myObj = {
        first : 'test1',
        second: 'test2',
    };
     
    console.log(myObj);
    // { first: 'test1', second: 'test2' }

     

     

     

    - Map & Set

     

    es6부터는 javascript에서도 Map과 Set을 지원한다

     

    - 예제 코드

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    // Map
     
    let map = new Map([['id','test']]);
    // map 선언 ( 앞이 key, 뒤가 value가 된다 )
    map.set('testId','test');
    // map에 key와 value 추가 ( 역시 앞이 key, 뒤가 value가 된다 )
     
    console.log(map);
    // Map { 'id' => 'test', 'testId' => 'test' }
     
    console.log(map.get('testId'));
    // test
    // key에 해당하는 value 출력
     
    console.log(map.size);
    // 2
    // map 크기 출력
     
    console.log(map.has('testId'));
    // true
    // map에 특정 key가 있는지 확인
     
    console.log(map.entries());
    // [Map Iterator] { [ 'id', 'test' ], [ 'testId', 'test' ] }
    // map안의 모든 요소를 key, value 형태의 array로 집어넣은 iterator 반환
     
    console.log(map.keys());
    // [Map Iterator] { 'id', 'testId' }
    // map안의 모든 key를 반환
     
    console.log(map.values());
    // [Map Iterator] { 'test', 'test' }
    // map안의 모든 value를 반환
     
    console.log(map.delete('testId'));
    // true
    // map 안에서 특정 key에 해당하는 key-value쌍 삭제
     
    console.log(map.size);
    // 1
    // map안의 모든 값 삭제
    console.log(map.size);
    // 0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    // Set
     
    const set = new Set([1,1,1,1,1,1,1,2,4,4,4,3,3,3]);
    // set 선언
    // set에 값 추가
    console.log(set);
    // Set { 1, 2, 4, 3, 5 }
    console.log(set.size);
    // 5 
     
    // Set은 중복을 허용하지 않는다
     
    set.delete(5);
    // Set에서 특정 값 삭제
    console.log(set.size);
    // 4
    // Set의 모든 값 삭제
    console.log(set.size);
    // 0

    - Async & Await

     

    es6에선 Async와 Await를 활용해서, promise then을 쓸 때 보다 좀 더 세련되게 callback 지옥을 벗어날 수 있다.

    ( Async & Await 에 관한 상세한 포스팅은 아래 참고 )

     

    [javascript] Promise, async, await - 개발자 황준일

    javascript는 event driven 으로 작동되며 이에 따라 비동기 프로그래밍 해야합니다. 즉, 이벤트가 끝난 후에 코드가 실행 되는 방식입니다. 이 때 많은 사람들이 callback 지옥을 직면하게 되며, promise를 통해 해결할 수 있습니다.

    junil-hwang.com

    - 예제 코드

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    function resolvePromise() {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve('done');
            }, 2000);
        })
    }
     
    async function getPromise1(){
        const result = await resolvePromise();
        console.log(result);
        // 2초 경과 후 done 
        await resolvePromise();
        console.log(result);
        // 2초 경과 후 done 
        await resolvePromise();
        console.log(result);
        // 2초 경과 후 done 
        await resolvePromise();
        console.log(result);
        // 2초 경과 후 done 
        await resolvePromise();
        console.log(result);
        // 2초 경과 후 done 
    }
     
    getPromise1();
    반응형

    댓글

Designed by Tistory.