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!

Constants in JavaScript

Many programming languages have the concept of a constant – a value that once declared can't be changed. There are many reasons why you'd want to do this, from security (if a third party script changed such values it could cause problems) to debugging and code comprehension (it is harder to accidentally change values that shouldn't be changed and mess things up).

In the early days of JavaScript, constants didn't exist. In modern JavaScript, we have the keyword const, which lets us store values that can never be changed:

const daysInWeek = 7;
const hoursInDay = 24;

const works in exactly the same way as let, except that you can't give a const a new value. In the following example, the second line would throw an error:

const daysInWeek = 7;
daysInWeek = 8;