Modern JavaScript syntax - ES6 constants

by Tekmi

HTML

<script src="https://getfirebug.com/firebug-lite-debug.js"></script>

Babel + JSX

/*
 |--------------------------------------------------------------------------
 | Const Primitive
 |--------------------------------------------------------------------------
 */

const PI = 3.14;

// Not possible, because initial value is missing
// const PI;

// Not possible to reassign
// PI = 3.12;

// Not possible to redeclare
// var PI = 3.14159265359

// Possible in IIFE, because it is in different context
(function() {
    const PI = 3.14159265359;
    // Will output 3.14159265359
    console.log(PI);
})();

// Possible, because it's in different block scope
if (true) {
    const PI = 3.14159;
    // Will output 3.14159
    console.log(PI);
}

// Not possible, because var variable gets hoisted
// if (true) { var PI = 3.14159; }

// Will output 3.14
console.log(PI);

/*
 |--------------------------------------------------------------------------
 | Const Array
 |--------------------------------------------------------------------------
 */

const PLANETS = ['Mercury', 'Venus', 'Earth', 'Mars'];

// Not possible to reassign
// PLANETS = ['Mercury'];

// Not possible to redeclare
// var PLANETS = [];

PLANETS[5] = 'Saturn';
delete PLANETS[0];
// Will output [undefined, 'Venus', 'Earth', 'Mars', undefined, 'Saturn']
console.log(PLANETS);

PLANETS.push('Jupiter');
// Will output [undefined, "Venus", "Earth", "Mars", undefined, "Saturn", "Jupiter"]
console.log(PLANETS);

PLANETS.pop();
PLANETS.pop();
PLANETS.pop();
PLANETS.shift();
// Will output ["Venus", "Earth", "Mars"]
console.log(PLANETS);

PLANETS.unshift('MERCURY');
// Will output ["MERCURY", "Venus", "Earth", "Mars"]
console.log(PLANETS);

PLANETS.length = 6;
// Will output ["MERCURY", "Venus", "Earth", "Mars", undefined, undefined]
console.log(PLANETS);

PLANETS.length = 1;
// Will output ["MERCURY"]
console.log(PLANETS);

/*
 |--------------------------------------------------------------------------
 | Const Object
 |--------------------------------------------------------------------------
...