Javascript tips — var, let, const and hoisting

Leonardo Bruno Lima
3 min readMar 21, 2018

--

Photo by Caspar Rubin on Unsplash

Scope is the key point to write javascript code. These keyword are simple, but often misunderstand, which leads some programmers to introduce serious bugs on code.

Before ES6 or ECMAScript 2015, the only way to declare a variable was using the keyword var. You can still use it, but now with ES6/ECMAScript 2015–2017 we have new keywords: let and const. We have thousands of articles and videos talking about javascript scope, what I want to do here is show examples and discuss to use of var, let and const.

First let’s make some concepts clear:

1 — Using {} (curly brace) doesn’t create context/scope unlike many languages like C#, Java, etc

2 — Hoisting is the way Javascript deal with variable (using the var keyword) and function declarations. Conceptually all variable (declared with var)and functions are moved to the top of the code, but this is not in fact what happens. The variable and function declarations are put into memory during the compile phase, but stays exactly where you typed it in your coding. Let’s see an example:

var x = 1;

function foo() {
console.log(x);
var x = 2;
console.log(x);
}

foo();

console.log(x);

What is the output of the code above? 1, 2, 1? humm, not really. the result is undefined, 2 and 1. Why? Because the hoisting. Javascript will “move” all variables decalration to top, so this code above will look like this:

var x = 1

function foo() {
var x;
console.log(x); // undefined
x = 2;
console.log(x); // 2
}

foo();

console.log(x); // 1

As you can see, only the declaration is “moved”, not the initialization. Ok, now we have this two concepts more clear, let’s talk about these keywords:

  • var keyword: As I showed previously, using var make us vulnerable to hoisting and I do not recommend to use it anymore.
  • let keyword: Is the new way to declare variable in ES6/ECMAScript 2015+. Using let we are not susceptible to the hoisting and the code above can be rewritten as:
let x = 1;

function foo() {
console.log(x); // ReferenceError: x is not defined
let x = 2;
console.log(x);
}

foo();

console.log(x);

In this case, as the let keyword is not susceptible to the hoisting, we will end up in an exception, because in fact the x variable was not declared before console.log(x) statement.

Another benefit of let is that you can create scope with blocks like {}, if, for, while, etc.

let x = 1;{
let x = 2
console.log(x)
}
console.log(x)

The output will be 2, 1. Now using var:

var x = 1;{
var x = 2
console.log(x)
}
console.log(x)

The output will be 2, 2.

  • const keyword: This keyword has the same behaviour of let, except it value cannot be changed and the variable need to be initialized.
const x = 1;{
const x = 2
console.log(x)
}
console.log(x)

The output will be 2, 1 alike the let statement.

Final consideration: You don’t have reason to not use let or const.

Thanks!

--

--