ES6 of the Week

Review: What is ES6 Anyway?

  • ECMAScript 6, also known as ECMAScript 2015, is the latest version of the ECMAScript standard. ES6 is a significant update to the language, and the first update to the language since ES5 was standardized in 2009.

ECMAScript? We're learning JavaScript, chief!

  • ECMAScript is a language specification that JavaScript follows (as do other languages like JScript, ActionScript, and more).
  • Standards like ECMAScript are pretty great - imagine having to learn a whole different dialect of JavaScript depending on which browser your code was running in. Thanks, ECMAScript!

This Week's Episode:

const and let

Block scope vs.

Function scope

  • Remember that, in Javascript,  var declares a  function-scoped variable.
  • Const and let set a tighter scoping - "block" scoping
    • Rather than being hoisted to the top of a function's scope, variables declared with  const and  let are hoisted only to the top of the code block
    • Forif,  while, try/catch all create code blocks
    • You can also create arbitrary code blocks, which can yield interesting use cases, particularly for garbage collection

Hoisting

function fooWithVar (bar) {
    if (bar) {
        var baz = 'baz'; 
    }
    console.log(baz);
}

// to the JavaScript interpreter:
function fooWithVar (bar) {
  var baz;
  if (bar) {
    baz = bar;
  }
  console.log(baz);
}

fooWithVar('hello world') // hello world
fooWithVar() // undefined

Blocked Out

function fooWithLet (bar) {
    if (bar) {
        let baz = 'baz'; 
    }
    console.log(baz);
}

// to the JavaScript interpreter:
function fooWithLet (bar) {
    if (bar) {
        let baz;
        baz = bar; 
    }
    console.log(baz);
}

fooWithLet(); // ReferenceError: baz is not defined


/** What's easier to debug: undefined, or a ReferenceError? */

Const

 

  • Declares a read-only reference to a value - all this means is that variables declared with "const" cannot be reassigned
  • Note that you can still modify the assigned content of the variable (ex. if you assign the variable to an object, you can still modify the object - you just can't assign that variable to something else, like another object)

Const Comment

'use strict';

const foo = [];
const bar = {};
const baz = 1;
const quux = 'hello';


foo.push(bar); // okay
bar.someMethod = function () {} // also okay

baz = 2 // TypeError: Assignment to constant variable
quux += ' world' // TypeError: Assignment to constant variable

"Letting" you in on a cool secret

// remember me from way back when?

function arrayOfFuncs(n) {
    let functions = [];

    /*  because using "let" to declare the variable "i" makes it block-scoped,
        you don't have to worry about it being closed over    */
    for (let i = 0; i < n; i++) {
        functions.push(function () {
            return i;
        });
    }
    return functions;
}

let myFunctions = arrayOfFuncs(5);
myFunctions[0]() // => 0    I work the way you thought I would!
myFunctions[1]() // => 1    Pretty cool, right?

Cleaning up

// the combination of let and arbitrary code blocks can help you free up memory faster

function suchCalculation () {
    /* very function */
}


/* Arbitrary code blocks are also new with ES6
   They prevent scope pollution - no need for a messy IIFE!
*/
{
    let muchData = { /* large dataset */ }
    suchCalculation(muchData);
}

/* At this point, the garbage collector will have cleaned up the large data set we used, 
   since we're outside the code block
*/

console.log('wow!');

Getting even deeper

  • In your browser JavaScript, you may notice that const and let do not create properties on your global window object, but var does!
  • The global environment is actually a composite of an object environment record and a declarative environment record
  • The OER === window. Accesible as a JS object
  • The DER is stored in an internal data structure, and isn't accessible.  
  • Only function declarations and variable declarations (using var) in the global scope are stored on the OER

Why Use Let and Const?

  • Safer, more descriptive way to declare your data
  • Protects your for loops from unwanted closure
  • Enforces good practice

Why Continue using Var?

  • Maybe browser compatibility, if you're in an environment where you can't use Babel
  • Otherwise...you can actually replace var with const and let entirely. The Airbnb javascript style guide actually recommends doing just that!

Resources

  • ES6: http://es6-features.org/
  • YDKJS: https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20&%20closures/ch3.md
  • Airbnb style guide: https://github.com/airbnb/javascript
  • Mozilla docs:
    • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let
    • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const
  • StackOverflow: http://stackoverflow.com/questions/28776079/do-let-statements-create-properties-on-the-global-object

ES6 of the Week - 1

By Tom Kelly

ES6 of the Week - 1

Const and Let

  • 1,377