190829 ES6(ECMA Script6)

zenibako.lee
11 min readAug 29, 2019

--

ES6 == ECMA Script 2015,ECMA Script6

Ecma International에 의해 정의되는 자바스크립트 실행의 규칙.

ES6 에서 추가된 규칙들.

let variable

var 변수는 선언 될 때 해당 변수의 스코프의 최상단에서 function-scope, hoist되지만
let의 경우 선언시 block-scope({})되고 hoist되지 않는다.
=for문 외부에서 i를 호출한다면, var은 가능, let은 불가능.

function-scope : 펑션 {} 내에 선언된 var변수는 해당 function과 동일한 scope를 갖는다.

hoist : 함수 선언전에 호출이 된 경우에도 사용이 가능하도록 선언을 끌어올림. but 변수는 초기화 라인(var x = 1;)말고 선언 라인(var x)만 끌어올림.

var x = 1; // x 초기화
console.log(x + " " + y); // '1 undefined'
var y = 2;

참고

https://developer.mozilla.org/ko/docs/Glossary/Hoisting

const variable

const변수는 선언과 동시에 read-only속성을 갖는다.

let과 마찬가지로 block-scope를 갖는다.

constant = 상수

const PERSON = {name: “Peter”, age: 28};const COLORS = [“red”, “green”, “blue”];

! 그러나 array나 object const의 경우

PERSON.name = ‘James’;COLORS[0] = ‘black’ 

위와 같이 value변화가 가능하다.

for…of Loop

string과 array의 경우 character, element단위로 호출 가능.

for(let letter of letters) { console.log(letter); // a,b,c,d,e,f }for(let character of greet) { console.log(character); // H,e,l,l,o, ,W,o,r,l,d,! }

object(key: ‘value’)의 경우 for…in 으로 사용.

for(let key in obj){console.log(key) // key1, key2 key3 …}

Template Literals

여러줄의 단일 string을 선언하거나, string안에서 변수를 사용할 경우.

back-tick ( ` ` )내부에 string을 넣어서 사용.

let str = `The quick brown fox
jumps over
the lazy dog.`; // str호출하면 개행 포함된 string 호출.
let a = 1; let b = 3; console.log(`The sum of ${a} and ${b} is ${a+b}.`)
es5 // console.log('The sum of ' + a + ' and ' + b + ' is ' + (a+b) + '.');
The sum of 1 and 3 is 4.

=> 각각 변수의 자리에 변수의 값이 호출되어 작동.

개인적으로는 eval(str) 을 통한 방식에 편리한듯..?

Arrow functions

=>(fat arrow)를 이용해 함수표현을 보다 간결하게 가능.

‘function’과 ‘return’을 생략하게 된다.

let sum = function sum(a,b){return a+b};// es5let sum =(a,b)=>a+b; //es6

! 그러나 arrow function으로 선언한 method의 경우

내부에서 this를 호출하면 Window가 나오게 된다.

const myObject = {
myMethod: () => {console.log(this);
}
};
myObject.myMethod() // Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}

const test = {
method : function(){console.log(this)}
}
test.method() // {method: ƒ}

arrow function으로 선언한 함수에서 this를 호출하는 방법은

아래와 같다.

const myObject = { 
myArrowFunction: null,
myMethod: function () {
this.myArrowFunction = () => { console.log(this) };
}
};
myObject.myMethod() // this === myObject
myObject.myArrowFunction() // this === myObject
const myArrowFunction = myObject.myArrowFunction; myArrowFunction() // this === myObject

참고

Class

class는 es6 이전버젼에서는 없는 키워드이지만, function을 이용해 유사한 방식으로 사용이 가능했다.

es6이후로는 ‘extends’를 이용해 상속을 받거나, instance를 보다 간편하게 생성할 수 있게 되었다.

class Rectangle { // Class constructor
constructor(length, width) {
this.length = length;
this.width = width;
}
// Class method
getArea() {
return this.length * this.width;
}
}
// Square class inherits from the Rectangle classclass Square extends Rectangle { // Child class constructor
constructor(length) {
// Call parent’s constructor
super(length, length); }
// Child class method
getPerimeter() { return 2 * (this.length + this.width); } }

Default parameter value

argument로 전달된 값이 없을 때, default로 전달될 값을 지정 가능하다.

function sayHello(name=’World’) {
return `Hello ${name}!`; }
function sayHello(name) {
var name = name || ‘World’;
return ‘Hello ‘ + name + ‘!’; }

Modules

es6이전에는 내장된 module 기능이 없었다.

따라서 자바스크립트내에 개별 파일들은 동일한 scope를 사용했다.

그러나 es6부터 .js파일기반으로 분리된 모듈을 제공하여 export, import를 이용해 변수 등등을 공유할 수 잇다.

main.js
let greet = “Hello World!”;
const PI = 3.14;
function multiplyNumbers(a, b) {
return a * b; }
// Exporting variables and functions
export { greet, PI, multiplyNumbers };
app.js
import { greet, PI, multiplyNumbers } from ‘./main.js’; alert(greet); // Hello World!
alert(PI); // 3.14
alert(multiplyNumbers(6, 15)); // 90

.html내에서 script태그를 이용해 browsing시에 사용이 가능하다.

<script type=”module” src=”app.js”></script>es5//
<script src="app.js"></script>

es5에서는 호출 되는 횟수(+load) 만큼 실행되지만,

module의 경우는 단 한번 실행된다.

참고

Rest Parameters

argument로 전달된 parameter를 array형식으로 묶어서 입력.

function myFunction(…args) { return args; } myFunction(1,2,3,4,5) // [1, 2, 3, 4, 5]function myFunction(a, b, …args) { return args; }
myFunction(1,2,3,4,5) // [ 3, 4, 5]

! REST (REpresentational State Transfer)는 아예 다릅니다.

RESTful web services와 전혀 관계가 없습니다.

spread operator

rest operator와 정반대의 기능을 수행.

입력받은 array를 element로 쪼개서 parameter로 입력.

let pets = [“Cat”, “Dog”, “Parrot”]; 
let bugs = [“Ant”, “Bee”];
// Creating an array by inserting elements from other arrays
let animals = […pets, “Tiger”, “Wolf”, “Zebra”, …bugs]; alert(animals); // Cat,Dog,Parrot,Tiger,Wolf,Zebra,Ant,Bee

Destructing Assignment

array 나 object에서 value를 extract하는 보다 간단한 방법이 es6에 추가되었다.

Array
let fruits = [“Apple”, “Banana”];
let [a, b] = fruits;
// Array destructuring assignment
alert(a); // Apple
alert(b); // Banana
//rest operator
let [a, ...r] = fruits;
alert(a); // Apple
alert(r); // Banana
alert(Array.isArray(r)); // true
object
let person = {name: “Peter”, age: 28};
let {name, age} = person;
// Object destructuring assignment
alert(name); // Peter
alert(age); // 28

추가된 메소드

new Number property

  • EPSILON
  • MIN_SAFE_INTEGER
  • MAX_SAFE_INTEGER

new Number method

  • Number.isInteger()
  • Number.isSafeInteger()

new Global method

  • isFinite()
  • isNaN()

Array.find()

조건에 맞는 첫번째 element를 extract. (filter 축소판?)

var numbers = [4, 9, 16, 25, 29];
var first = numbers.find(myFunction);
function myFunction(value, index, array) {
return value > 18;
} --> 25

Araay.findIndex()

조건에 맞는 첫번째 엘리먼트의 index return

var numbers = [4, 9, 16, 25, 29];
var first = numbers.findIndex(myFunction);
function myFunction(value, index, array) {
return value > 18;
} --> 2

Exponentiation Operator

n제곱 계산을 더 편리하게 가능해졌다. x**n

var x = 5;var es5 = Math.pow(x,3);var es6 = x**3; 

--

--

zenibako.lee
zenibako.lee

Written by zenibako.lee

backend engineer, JS, Node, AWS

No responses yet