06.07.2017 Views

Mastering JavaScript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

ECMAScript 6<br />

Using standalone brackets {} may seem unusual in <strong>JavaScript</strong>, but this convention is<br />

fairly common to create a block scope in many languages. The block scope kicks in<br />

other constructs such as if { } or for (){ } as well.<br />

When you use a block scope in this way, it is generally preferred to put the variable<br />

declaration on top of the block. One difference between variables declared using<br />

var and let is that variables declared with var are attached to the entire function<br />

scope, while variables declared using let are attached to the block scope and they<br />

are not initialized until they appear in the block. Hence, you cannot access a variable<br />

declared with let earlier than its declaration, whereas with variables declared using<br />

var, the ordering doesn't matter:<br />

function fooey() {<br />

console.log(foo); // ReferenceError<br />

let foo = 5000;<br />

}<br />

One specific use of let is in for loops. When we use a variable declared using<br />

var in a for loop, it is created in the global or parent scope. We can create a blockscoped<br />

variable in the for loop scope by declaring a variable using let. Consider the<br />

following example:<br />

for (let i = 0; i

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

Saved successfully!

Ooh no, something went wrong!