Published on

A Review of ES6 - Constants, Scoping, Arrow Functions

Constants

Constants

Support for constants (also known as "immutable variables"), i.e., variables which cannot be re-assigned new content. Notice: this only makes the variable itself immutable, not its assigned content (for instance, in case the content is an object, this means the object itself can still be altered).

const PI = 3.141593
PI > 3.0

Scoping

Block-Scoped Variables

Block-scoped variables (and constants) without hoisting.

for (let i = 0; i < a.length; i++) {
    let x = a[i]
}
for (let i = 0; i < b.length; i++) {
    let y = b[i]
}

let callbacks = []
for (let i = 0; i <= 2; i++) {
    callbacks[i] = function () { return i * 2 }
}
callbacks[0]() === 0
callbacks[1]() === 2
callbacks[2]() === 4

Block-Scoped Functions

{
    function foo () { return 1 }
    foo() === 1
    {
        function foo () { return 2 }
        foo() === 2
    }
    foo() === 1
}

Arrow Functions

Expression Bodies

More expressive closure syntax.

odds  = evens.map(v => v + 1)
pairs = evens.map(v => ({ even: v, odd: v + 1 }))
nums  = evens.map((v, i) => v + i)

Statement Bodies

More expressive closure syntax.

nums.forEach(v => {
   if (v % 5 === 0)
       fives.push(v)
})

Lexical this

More intuitive handling of current object context.

this.nums.forEach((v) => {
    if (v % 5 === 0)
        this.fives.push(v)
})

References: