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!

Dynamic typing

JavaScript is a "dynamically typed language", which means that, unlike some other languages, you don't need to specify what data type a variable will contain (numbers, strings, arrays, etc).

For example, if you declare a variable and give it a value enclosed in quotes, the browser treats the variable as a string:

let myString = 'Hello';

Even if the value contains numbers, it is still a string, so be careful:

let myNumber = '500'; // oops, this is still a string
typeof myNumber;
myNumber = 500; // much better – now this is a number
typeof myNumber;

Try entering the four lines above into your console one by one, and see what the results are. You'll notice that we are using a special operator called typeof – this returns the data type of the variable you type after it. The first time it is called, it should return string, as at that point the myNumber variable contains a string, '500'. Have a look and see what it returns the second time you call it.