Practice Review: Using "var", "let", and "const" Statements

Try this exercise to see how well you understood this unit. 

Read this article while opening a Developer Console in your browser. The sequence is ctrl+shift+J on Windows and cmd+option+J on the Mac. Type in each statement and examine the output using the Console tab. 

After reading this article, consider these questions:

  • What is the difference between the "var", "let", and "const" keywords?
  • What is "var" hoisting?
  • Should "dynamic typing" be used in your JavaScript programs?

This exercise does not count towards your grade. It is just for practice!

The difference between var and let

At this point you may be thinking "why do we need two keywords for defining variables?? Why have var and let?".

The reasons are somewhat historical. Back when JavaScript was first created, there was only var. This works basically fine in most cases, but it has some issues in the way it works – its design can sometimes be confusing or downright annoying. So, let was created in modern versions of JavaScript, a new keyword for creating variables that works somewhat differently to var, fixing its issues in the process.

A couple of simple differences are explained below. We won't go into all the differences now, but you'll start to discover them as you learn more about JavaScript.

For a start, if you write a multiline JavaScript program that declares and initializes a variable, you can actually declare a variable with var after you initialize it and it will still work. For example:

myName = 'Chris';

function logName() {
  console.log(myName);
}

logName();

var myName;

Note: This won't work when typing individual lines into a JavaScript console, just when running multiple lines of JavaScript in a web document.

This works because of hoisting.

Hoisting no longer works with let. If we changed var to let in the above example, it would fail with an error. This is a good thing– declaring a variable after you initialize it results in confusing, harder to understand code.

Secondly, when you use var, you can declare the same variable as many times as you like, but with let you can't. The following would work:

var myName = 'Chris';
var myName = 'Bob';

But the following would throw an error on the second line:

let myName = 'Chris';
let myName = 'Bob';

You'd have to do this instead:

let myName = 'Chris';
myName = 'Bob';

Again, this is a sensible language decision. There is no reason to redeclare variables – it just makes things more confusing.

For these reasons and more, we recommend that you use let as much as possible in your code, rather than var. There is no reason to use var, unless you need to support old versions of Internet Explorer with your code (it doesn't support let until version 11; the modern Microsoft Edge browser supports let just fine).