ECMAScript? We're learning JavaScript, chief!
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
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? */
'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
// 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?
// 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!');