sainture
4/3/2016 - 7:19 AM

ECMA 6 Constants, and Block Scoped Variables

ECMA 6 Constants, and Block Scoped Variables

/* ES6 introduces the concept of block scoping using 'let' instead of 'var'
let vs var
The difference is scoping. var is scoped to the nearest function block 
(or global if outside a function block), and let is scoped to the nearest enclosing block
(or global if outside any block), which can be smaller than a function block.

Global:
They are very similar when used like this outside a function block.
*/
let me = 'go'; // globally scoped
var i = 'able'; // globally scoped

/* However, global variables defined with let will not be added as properties on the global window
object like those defined with var.*/
console.log(window.me); // undefined
console.log(window.i); // 'able'


/*Function:
They are identical when used like this in a function block.*/
function ingWithinEstablishedParameters() {
    let terOfRecommendation = 'awesome worker!'; //function block scoped
    var sityCheerleading = 'go!'; //function block scoped
};

/*Block:
Here is the difference. let is only visible in the for() loop and var is visible
to the whole function.*/
function allyIlliterate() {
    //tuce is *not* visible out here

    for( let tuce = 0; tuce < 5; tuce++ ) {
        //tuce is only visible in here (and in the for() parentheses)
    };

    //tuce is *not* visible out here
};

function byE40() {
    //nish *is* visible out here

    for( var nish = 0; nish < 5; nish++ ) {
        //nish is visible to the whole function
    };

    //nish *is* visible out here
};

// Despite the introduction of block scoping, functions are still the preferred mechanism for
// dealing with most loops.

/* Alternatively, const is read only. Once const has been assigned, the identifier can not be
re-assigned
*/

const myName = 'pat';
let yourName = 'jo';
yourName = 'sam'; // assigns
myName = 'jan'; // error


// const
// const and let use { and } blocks as containers, hence "block scope".
// const is read-only. Once const has been assigned, the identifier cannot be reassigned.

const myName = 'pat';
let yourName = 'jo';

yourName = 'sam'; // assigns
myName = 'jan';   // error

// The read-only nature can be demonstrated with any object
const literal = {};

literal.attribute = 'test'; // fine
literal = []; // error;

// another example
const person = {
  name: 'Tammy'
};

person.name = 'Pushpa'; // OK, name property changed.

person = null;          // "TypeError: Assignment to constant variable.

// Important: marking an object reference const does not make properties inside the object const.