-
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키 위에 있는 ` 다. 작은 따옴표 아님 )
- 예제 코드
12345678910111213141516const val1 = 'my string';const val2 = 'my string2';// es5const conVal = val1 + ', '+ val2;console.log(conVal);// my string, my string2// es6const litVal = `${val1}, ${val2}`console.log(litVal);// my string, my string2- 객체 비구조화 ( Object Destructuring )
객체에 들어있는 값들 각각을 꺼내 쓸 수 있다.
- 예제 코드
1234567891011121314151617181920const 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 Koreaconsole.log(city);// Seoulconsole.log(street);// Gangnamconsole.log(str_num);// 141console.log(postcode);// 00510- 객체 리터럴 ( Object Literal )
ES6에선 객체 프로퍼티 이름이 로컬 변수 이름과 같으면 콜론과 값 없이 작성해도 된다.
값을 직접 명시해주는 경우와 함께 사용할 수도 있다
- 예제 코드
1234567891011121314151617function 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에 추가된 효율적인 반복문이다
- 예제코드
123456789101112131415161718192021222324252627282930313233343536let years = [2001, 2010,2015, 2018];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 6for(let year of years){console.log(year);// 2001if(year == 2001){break;}// 내부에서 break 문 사용 가능}for(let char of str){console.log(char);// T, e, s, t}- Spread Operator
배열이나 객체, 문자열을 ...과 함께 사용하면 배열, 객체, 문자열을 결합하기가 매우 수월해졌습니다.
- 예제코드
123456789101112131415161718192021// Spread Operateorlet years = [2001, 2010,2015, 2018];console.log(yearsCp);// [ 2000, 2001, 2010, 2015, 2018, 2020 ]let koreanHistory = {liberate : 1945,625: 1950};let history = {worldWar1: 1914,worldWar2: 1945,... koreanHistory}console.log(history);// { '625': 1950, worldWar1: 1914, worldWar2: 1945, liberate: 1945 }- Rest Parameter
... 을 함수의 인자에 사용하면 인자를 배열로 받을 수 있다
- 예제코드
12345678910111213function printYears(years) {console.log(years);// 2000}printYears(2000, 2001, 2010, 2015, 2018);function printYearsWithRestParameter(...years){console.log(years);// [ 2000, 2001, 2010, 2015, 2018 ]}printYearsWithRestParameter(2000, 2001, 2010, 2015, 2018);- Arrow Function
Arrow Function을 활용하면 함수 표현을 기존의 function 표현보다 짧은 구문으로 표현할 수 있다.
- 예제 코드
12345678910111213141516171819202122232425262728293031323334const years = [{year: 2000,data: '크리스마스',},{year: 2001,data: '로스트메모리즈',},{year: 2002,data: '월드컵',},{year: 2015,data: '리액트네이티브',},{year: 2019,data: '올해',},];});console.log(result);// [ { year: 2015, data: '리액트네이티브' }, { year: 2019, data: '올해' } ]console.log(arrowReulst);// [ { year: 2015, data: '리액트네이티브' }, { year: 2019, data: '올해' } ]- Default Params
es6에선 함수의 기본 파라미터를 세팅해줄 수 있다.
- 예제코드
12345678910111213141516171819202122232425262728293031323334353637383940414243444546const 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를 활용하면 배열에 특정값이 있는지를 깔끔하게 확인할 수 있다.
- 예제 코드
12345678910111213141516let years = [2001,2010,2015, 2018];const fruits = ['apple','banana','potato'];// es5console.log(years.indexOf(2014) !== -1);// falseconsole.log(fruits.indexOf('apple') !== -1);// true// es6console.log(fruits.includes('appl'));// falseconsole.log(fruits.includes('apple'));// true- let & const
es5에선 변수를 var로만 선언할 수 있었다. 그러나 es6에서 let과 const가 추가되었다.
let과 const를 활용하면 예상하지 못한 오류가 발생하는 걸 막을 수 있다. 이를 사용하길 권장한다.
( var, let, const 차이에 관한 상세한 포스팅은 아래 참고)
- 예제 코드
123456789101112131415161718192021// var 과 let의 차이if(true) {var varId = 'test';// var로 선언}console.log(varId);// test// scope가 다른데도 varId가 출력된다if(true) {let hoistingId = 'test';// let으로 선언}// error로 실행 불가// scopre가 다르기 때문에 당연히 에러 발생// let과 const의 차이123456789101112// let과 const 차이let letId = 'testBefore';letId = 'testAfter';console.log(letId);// testAfterconst constId = 'testBefore';//constId = 'testAfter';// const로 선언된 변수를 재할당 하려하면 error 발생으로 실행불가// 즉 const 로 선언된 변수의 값은 변하지 않는다.1234567891011121314151617// const로 객체와 배열을 선언했을 때 예외사항const fruit = {};// fruit = {test : 'apple'};// fruit 값을 직접 바꾸려 하면 에러가 발생하지만console.log(fruit);// { first: 'apple' }// 위와 같은 방식으로 객체 내부의 값을 바꾸는 것은 가능하다.const numbers = [0,1,2];numbers[0] = 5;console.log(numbers);// [ 5, 1, 2 ]// 배열도 객체와 마찬가지다- import & export
import와 export를 활용하면 다른 파일에서 사용한 원시값, 객체, 배열, 함수 등을 가져와서 쓸 수 있다.
- 예제 코드
123412345// import.jsimport { fruits, test } from './export.js';console.log(fruits, test);// [ 'apple', 'banana', 'potato' ] 'test입니다'- Classes
es5에서 어떤 함수를 Class처럼 쓰려면 함수를 Class처럼 만들고 prototype을 활용해야 했지만
es6부터는 객체지향형 프로그래밍 언어들이 지원하던 Class를 javascript에서도 사용할 수 있게 되었다.
- 예제 코드
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263//es5function Animal() {}Animal.prototype.setType = function (type) {this.type = type;}Animal.prototype.getType = function () {return this.type;}// es6class 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');// woofAni.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는 데이터가 늘어날 경우를 대비해서 사용한다 )
- 예제 코드
1234567const myObj = {first : 'test1',second: 'test2',};console.log(myObj);// { first: 'test1', second: 'test2' }- Map & Set
es6부터는 javascript에서도 Map과 Set을 지원한다
- 예제 코드
1234567891011121314151617181920212223242526272829303132333435363738394041424344// Maplet map = new Map([['id','test']]);// map 선언 ( 앞이 key, 뒤가 value가 된다 )// map에 key와 value 추가 ( 역시 앞이 key, 뒤가 value가 된다 )console.log(map);// Map { 'id' => 'test', 'testId' => 'test' }// test// key에 해당하는 value 출력console.log(map.size);// 2// map 크기 출력// 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);// 012345678910111213141516171819202122// Setconst set = new Set([1,1,1,1,1,1,1,2,4,4,4,3,3,3]);// set 선언set.add(4);set.add(5);// 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 에 관한 상세한 포스팅은 아래 참고 )
- 예제 코드
123456789101112131415161718192021222324252627function resolvePromise() {return new Promise((resolve, reject) => {setTimeout(() => {resolve('done');}, 2000);})}async function getPromise1(){const result = await resolvePromise();console.log(result);// 2초 경과 후 doneawait resolvePromise();console.log(result);// 2초 경과 후 doneawait resolvePromise();console.log(result);// 2초 경과 후 doneawait resolvePromise();console.log(result);// 2초 경과 후 doneawait resolvePromise();console.log(result);// 2초 경과 후 done}getPromise1();반응형'Knowledge > javascript' 카테고리의 다른 글
map을 사용했는데 의도하지 않은 쉼표가 출력된다면? (0) 2022.01.06 자바스크립트 모듈(Module) 학습 내용 간단 요약 (0) 2020.05.03 자바스크립트에서 이미지 파일( form data ) 을 ajax로 넘기는 방법! (0) 2019.09.18 javascript this와 bind (0) 2019.09.15 javascript 객체 리터럴 패턴과 생성자 패턴, prototype (0) 2019.09.09