Syntax

Functions

Built-ins

Professional Developer

02. Let and Const

There are now two new ways to declare variables in JavaScript: let and const.

Up until now, the only way to declare a variable in JavaScript was to use the keyword var. To understand why let and const were added, it’s probably best to look at an example of when using var can get us into trouble.

Take a look at the following code.

Hoisted to the Top

What do you expect to be the output from running getClothing(false)?

function getClothing(isCold) {
  if (isCold) {
    var freezing = 'Grab a jacket!';
  } else {
    var hot = 'It’s a shorts kind of day.';
    console.log(freezing);
  }
}

ReferenceError: freezing is not defined

Grab a jacket!

undefined

It’s a shorts kind of day.

SOLUTION:

undefined

 

 

Hoisting

Hoisting is a result of how JavaScript is interpreted by your browser. Essentially, before any JavaScript code is executed, all variables are “hoisted”, which means they’re raised to the top of the function scope. So at run-time, the getClothing() function actually looks more like this…

INSTRUCTOR NOTE:

Before the function is executed, all variables are hoisted to the top of the function scope. So what’s our solution?

Black Friday - Get 50% off

X