TIL5 | [자바스크립트] ES6
ES6
에 대해서 알아보자 ES는ECMA Script
의 줄임말이다. javascript를 표준화시키고 규격화하기 위해 만들어졌다. ES10까지 나왔으며 주로ES6를 쓴다.
ES6을 잘 활용한다면 코드 가독성을 올릴 수 있다.
Arrow function
ES6
의 대표적인 함수 사용법이다. function 표현에 비해 구문이 짧고 자신의 this, arguments, super
또는 new.target을 바인딩 하지 않는다. 화살표 함수는 항상 익명
이다. 이 함수 표현은 메소드 함수가 아닌 곳에 가장 적합하다. 그래서 생성자로서 사용할 수 없다.
const materials = [
'Hydrogen',
'Helium',
'Lithium',
'Beryllium'
];
console.log(materials.map(material => material.length));
// expected output: Array [8, 6, 7, 9]
매개변수가 있는 함수
//ES5
const getName = function(name) {}
//ES6
const getName = (name) => {}
const getName = name => {}
💡 TIP
인자가 하나
일 때는 소괄호 생략이 가능하지만
, 인자가 두 개
일 때는 생략할 수 없다.
콜백 함수에서의 활용
var numbers = [1, 4, 9];
var oddArr = numbers.filter( x => (x % 2) !== 0 );
console.log(oddArr); // [1, 9]
💡 TIP
화살표 함수 this
는 바깥 함수에 접근하여 사용된다.
활용 코드
let a = {
sound: "k",
soundPlay: function () {
setTimeout(() => {
console.log(this.sound);
}, 1000);
}
}
a.soundPlay();
// 1초 후에 "k"
template literals
back tick
string을 작성할 때 따옴표
를 사용했었지만,
const name = '개발자';
ES6
부터는 back tick
으로도 string
을 감쌀 수 있다.
const name = `개발자`;
back tick 으로 감싸면 그 안에 변수를 넣어서 표현
할 수 있다.( ${} 을 활용! )
const name = '개발자';
const hi = `안녕하세요. 저는 ${name} 입니다.`;
back tick
을 활용하면 break line
을 보다 편리하게 활용이 가능하다.
let detail = `안녕
나는
개발자`;
console.log(detail);
string methods
ES6에서는 string에서 특정 string을 찾기 위해 사용했던 indexOf를 대신할 3가지 method가 등장했다. 아래 이름이 훨씬 직관적이어서 기능을 파악하기 쉽다.
- startsWith
- endsWith
- includes
const email = '[email protected]';
console.log(email.startsWith('tmdckszm')); // true
console.log(email.endsWith('com')); // true
console.log(email.includes('@gmail')); // true
출처
https://ko.javascript.info/arrow-functions-basics
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Functions/Arrow_functions
Author And Source
이 문제에 관하여(TIL5 | [자바스크립트] ES6), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@tmdckzm/자바스크립트-Arrow-function저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)