06.07.2017 Views

Mastering JavaScript

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

We will cover the most important part of ES6 specifications in this chapter. You<br />

should explore all the features of ES6 if possible and make them part of your<br />

development workflow.<br />

Chapter 7<br />

ES6 syntax changes<br />

ES6 brings in significant syntactic changes to <strong>JavaScript</strong>. These changes need careful<br />

study and some getting used to. In this section, we will study some of the most<br />

important syntax changes and see how you can use Babel to start using these newer<br />

constructs in your code right away.<br />

Block scoping<br />

We discussed earlier that the variables in <strong>JavaScript</strong> are function-scoped. Variables<br />

created in a nested scope are available to the entire function. Several programming<br />

languages provide you with a default block scope where any variable declared<br />

within a block of code (usually delimited by {}) is scoped (available) only within this<br />

block. To achieve a similar block scope in <strong>JavaScript</strong>, a prevalent method is to use<br />

immediately-invoked function expressions (IIFE). Consider the following example:<br />

var a = 1;<br />

(function blockscope(){<br />

var a = 2;<br />

console.log(a); // 2<br />

})();<br />

console.log(a); // 1<br />

Using the IIFE, we are creating a block scope for the a variable. When a variable is<br />

declared in the IIFE, its scope is restricted within the function. This is the traditional<br />

way of simulating the block scope. ES6 supports block scoping without using IIFEs.<br />

In ES6, you can enclose any statement(s) in a block defined by {}. Instead of using<br />

var, you can declare a variable using let to define the block scope. The preceding<br />

example can be rewritten using ES6 block scopes as follows:<br />

"use strict";<br />

var a = 1;<br />

{<br />

let a = 2;<br />

console.log( a ); // 2<br />

}<br />

console.log( a ); // 1<br />

[ 165 ]<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!