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!

Declaring a variable

To use a variable, you've first got to create it – more accurately, we call this declaring the variable. To do this, we type the keyword var or let followed by the name you want to call your variable:

let myName;
let myAge;

Here we're creating two variables called myName and myAge. Try typing these lines into your web browser's console. After that, try creating a variable (or two) with your own name choices.

Note: In JavaScript, all code instructions should end with a semi-colon (;) – your code may work correctly for single lines, but probably won't when you are writing multiple lines of code together. Try to get into the habit of including it.

You can test whether these values now exist in the execution environment by typing just the variable's name, e.g.

myName;
myAge;

They currently have no value; they are empty containers. When you enter the variable names, you should get a value of undefined returned. If they don't exist, you'll get an error message – try typing in

scoobyDoo;

Note: Don't confuse a variable that exists but has no defined value with a variable that doesn't exist at all – they are very different things. In the box analogy you saw above, not existing would mean there's no box (variable) for a value to go in. No value defined would mean that there is a box, but it has no value inside it.


Source: Mozilla, https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Variables#declaring_a_variable
Creative Commons License This work is licensed under a Creative Commons Attribution-ShareAlike 2.5 License.