What’s new in ES6

laziel
5 min readOct 26, 2015

--

This is summarized “Ch.2 Knowing Your Library” of Learning ECMAScript 6.

Number

  • Binary notation: prefix the number the 0b (zero,b)token to make JavaScript interpret them as binary.
  • Octal notation: prefix the the 0 (zero) to represent as octal number.

16진수를 0x (zero,x) prefix 를 붙여서 표현했던 것 처럼, 2진수는 0b 를 붙여서, 8진수는 앞에 0 를 붙여서 표현할 수 있게 되었습니다. 단, 0(zero) 만을 붙이면 10진수와 혼동될 위험이 있어 0o(zero,o) 역시 8진수를 나타내는 prefix 로 사용할 수 있습니다.

  • Number.isInteger()
    Number.isInteger(17.0) === true
    Number.isInteger(1.2) === false

!isNaN(n) && (parseInt(n, 10) === n) 대신 Number.isInteger(n)

  • Number.isNaN() vs window.isNaN()
    Number.isNaN(“NaN”) === false, isNaN(“NaN”) === true
    Number.isNaN(NaN) === true, isNaN(NaN) === true
    Number.isNaN(“str”) === false, isNaN(“str”) === true
    Number.isNaN(1234) === false, usNaN(1234) === false
  • Number.isFinite() vs. window.isFinite()
    Number.isFinite(1234) === true, window.isFinite(1234) === true
    Number.isFinite(NaN) === false, window.isFinite(NaN) === false
    Number.isFinite(null) === false, window.isFinite(null) === true
    Number.isFinite([]) === false, window.isFinite([]) === true

isNaN(), isFinite() 외에 Number.isNaN(), window.isFinite() 가 추가되었습니다. 둘 사이 동작의 차이는 위 예시와 같습니다.

  • Number.isSafeInteger()
    Number.MIN_SAFE_INTEGER <= n <= Number.MAX_SAFE_INTEGER
  • Number.EPSILON: approximately 2^-52 which represents a reasonable margin of error when comparing the floating-point numbers.

안전한 숫자 표현, 오차범위 내에서의 숫자 비교를 위한 방법들입니다. 실수 연산 과정에서 2진수/10진수 변환으로 (부동소수점/고정소수점) 발생하는 오차를 Number.EPSILON 이란 상수로 제공함으로서 오차 범위를 고려한 결과 확인이 가능합니다. 참고: http://karmainearth.tistory.com/143

Math

  • Trigonometric operations: hyperbolic functions
    (sinh, cosh, tanh, asinh, acosh, atanh)
  • Pythagoras theorem: Math.hypot(2, 2, 1) === 3
    returns the square root of the sum of squares of its arguments
    Math.hypot(v1,v2,…,vn)=∑i=1nvi2=v12+v22+…+vn2
  • Arithmetic operations:
    - Math.log2(), Math.log10(): log() base 2, 10.
    - Math.log1p(v) === Math.log(1 + v)
    - Math.expm1() : inverse of Math.log1p()
    - Math.cbrt(): cube root

삼각함수, 피타고라스 정리 등 산술 연산 함수가 추가되었습니다.

  • Math.imul(a, b) : a * b in 32bit integer.
    Math.imul(590, 5000000) === -1344967296 // 32bit integer
    (590 * 5000000) === 2950000000 // 64bit floating point
  • Math.clz32(x): clz32 is short for CountLeadingZeroes32. This function is particularly useful for systems that compile to JS, like Emscripten.
    - If x is not a number, then it will be converted to a number first, then converted to a 32-bit unsigned integer.
    - If the converted 32-bit unsigned integer is 0, then return 32, because all bits are 0.
    [Reference: MDN]
  • Math.sign(): returns the sign of a number
    Math.sign(111) === 1
    Math.sign(-11) === -1
    Math.sign(0) === 0
  • Math.trunc(): returns the integer part of a number.
    Math.trunc(42.84) === 42
    Math.round(42.84) === 43

이전에는 정수부를 얻기 위해 parseInt(), Math.round(), Math.floor() 등을 이용하여 구현이 필요했으나 Math.trunc() 를 이용하면 음수(-)에 대한 고민없이 숫자의 정수부를 얻을 수 있습니다.

  • Math.fround(): returns the nearest single precision float representation of a number.
    Math.fround(1.337); === 1.3370000123977661

String

  • Unicode code point escapes: \u{···}. With a Unicode code point escape you can specify code points greater than 16 bits directly
    ‘\uD83D\uDE80’ === ‘\u{1F680}’
    ‘\uD83D\uDE91’ === ‘\u{1F691}’
  • String.fromCodePoint(): returns a string created by using the specified sequence of code points.
    String.fromCodePoint(65, 90) === ‘AZ’
  • String.prototype.codePointAt(): returns a non-negative integer that is the UTF-16 encoded code point value
  • String.prototype.repeat(n): returns a new string which has repeated n times of the string.
  • String.prototype.includes(needleString, [positionBegin]):
    ===
    “Haystack string”.indexOf(needleString) >= positionBegin
  • String.prototype.startsWith(string, index):
    === “Haystack string”.indexOf(needleString) === (0 || index)
  • String.prototype.endsWith(needleString, [positionEnd]):
    === new RegExp(needleString + ‘$’).test(haystackString.substr(0, positionEnd))
  • String.prototype.normalize([form]): returns the Unicode Normalization Form of a given string
    var a = “\u00E9”;
    var b = “e\u0301”;
    (a == b) === false;
    (a.normalize() == b.normalize()) === true;
  • Template Strings: `${expression}`
    - basic usage:

- processor function:
function some_func(str, …vals) { return str; }
console.log(some_func `template string`);
- Variables in expression should be defined before the template string.

  • Multiline: new line character will be preserved in a template string definition.
    console.log(`test
    \nasdf`);
    =>
    test
    asdf
  • String.raw: returns a raw string which is no escaped characters interpreted.
    String.raw `xy\n${1+1}` === ‘xy\n2’

Array

  • Array.from(iterable, mapFunction, this): creates a new array instance from an iterable object. iterable: String, Array, Map, Set, arguments, DOM data structure. (plain objects are not iterable). [Reference]
    var str = “test”;
    Array.from(str, function(v) { return v; });
    // = [‘t’, ‘e’, ‘s’, ‘t’]; = str.split(‘’);
  • Array.of(…):
    Array.of(1,2,3,4); //= [1,2,3,4]
  • Array.prototype.fill(value, startIndex, endIndex): fills the elements of the array from startIndex to endIndex(not including endIndex) with given value.
  • Array.prototype.find(testingFunction, this): returns an array element which the provided testingFunction returned true first.
    [1,2,3,4].find(function (n) { return n % 2;}); === 2

.find() 는 .filter() 와 비슷하게 특정 조건을 만족하는 원소를 반환하는데, .filter() 는 해당 조건을 만족하는 원소들의 집합(배열)을 반환하지만, .find() 는 그 중 첫 번째 원소만을 반환합니다.

  • Array.prototype.findIndex(testingFunction, this): Same with .find() but .findIndex() returns an index of the element while .find() returns the element itself.
  • Array.prototype.copyWithin(target, start, end):
    [1,2,3,4,5].copyWithin(0, 1, 3) // = [2,3,3,4,5]. copy [start ~ before end] at target.

.copyWithin() 은 target index 위치(부터)에, start 부터 end index직전까지의 값을 복사하여 덮어씁니다. 반환하는 값은 배열 그 자신이며 새로운 배열을 생성하는 것이 아니라 해당 배열에 대해 수행하는 작업입니다 (.sort 처럼).

  • in Array [‘a’, ‘b’, ‘c’]:
    Array.prototype.entries
    (): [[0, ‘a’], [1, ‘b’], [2, ‘c’]]
    Array.prototype.keys(): [0, 1, 2]
    Array.prototype.values(): [‘a’, ‘b’, ‘c’] // not available in Chrome

Collections

  • ArrayBuffer: generic, fixed-length raw binary data buffer. You cannot directly manipulate the contents in it. Creating one of the Typed Array objects or a DataView is needed to read/write the contents of the buffer.
  • DataView: provides a low-level interface for reading and writing multiple number types in an ArrayBuffer.
  • Typed Array: Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array.
  • Set: a collection of unique values of any data type.
    let set = new Set();
    for(var i =0; i < 5; i++) { set.add(1); }
    set.size === 1;
  • WeakSet: exactly same with a Set except that:
    - only store object references.
    - stored object will be GC when no other reference of them exists.
    - not enumerable.

Set, WeakSet 은 Array 와 비슷하지만 value 가 unique 하다는 점에서 차이가 있습니다. Set 은 enumerable 하지만 WeakSet 은 enumerable 하지 않다는 점 정도가 큰 차이입니다.

  • Map: a collection of key/value pairs. similar to HashMap of Java.
  • WeakMap: exactly same with a Map except that:
    - keys can only be object references
    - GC object when no other reference of them exists. similar to WeakSet.
    - not enumerable. like as WeakSet.

Map, WeakMap 은 key/value pair 데이터 타입이라는 점에서 Object 와 유사합니다. Set 과 마찬가지로 Map 은 enumerable 하지만, WeakMap 은 enumerable 하지 않습니다.

Object

  • __proto__ property to make working with prototypes easier with:
    - Object.getPrototypeOf(obj);
    - Object.setPrototypeOf(obj, parent);
    let test = {a: 11, __proto__: { b: 13 }};
    Object.getPrototypeOf(a); // = {b: 13}
    Object.setPrototypeOf({c: 12}, a); // = {c: 12, __proto__: {b: 13}}
  • Object.is(a, b): returns boolean whether a and b are equal or not. almost same with === operator but +0/-0 and NaN is the special case.
    (0 === -0) === true, Object.is(0, -0) === false
    (0/0 === NaN) === false, Object.is(0/0, NaN) === true
    (NaN === NaN) === false, Object.is(NaN, NaN) === true
    ({a:1} === {a:1}) === false, Object.is({a:1}, {a:1}) === false

두 객체가 동일한지를 판정하는 것으로 === 연산자와 거의 동일합니다.
객체의 내용이 동일하더라도(= 같은 속성, 같은 값을 갖더라도) 여전히 Object.is(a, b) 의 결과는 false 를 반환합니다.

  • Object.assign(target, …sources): copy the values of all enumerable own properties from one or more source objects to a target object.

이전에는 객체의 상속을 흉내내기 위해 아래와 같은 방법을 종종 사용했습니다. 클래스 구현은 이제 명시적으로 class 를 사용할 수 있으며, 객체의 property 를 다른 객체에 복제하려면 Object.assign(target, source1, source2…); 의 형태로 간단히 사용할 수 있습니다.

--

--