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!

Updating a variable

Once a variable has been initialized with a value, you can change (or update) that value by giving it a different value. Try entering the following lines into your console:

myName = 'Bob';
myAge = 40;


An aside on variable naming rules

You can call a variable pretty much anything you like, but there are limitations. Generally, you should stick to just using Latin characters (0-9, a-z, A-Z) and the underscore character.

  • You shouldn't use other characters because they may cause errors or be hard to understand for an international audience.
  • Don't use underscores at the start of variable names – this is used in certain JavaScript constructs to mean specific things, so may get confusing.
  • Don't use numbers at the start of variables. This isn't allowed and causes an error.
  • A safe convention to stick to is so-called "lower camel case", where you stick together multiple words, using lower case for the whole first word and then capitalize subsequent words. We've been using this for our variable names in the article so far.
  • Make variable names intuitive, so they describe the data they contain. Don't just use single letters/numbers, or big long phrases.
  • Variables are case sensitive – so myage is a different variable from myAge.
  • One last point: you also need to avoid using JavaScript reserved words as your variable names – by this, we mean the words that make up the actual syntax of JavaScript! So, you can't use words like var, function, let, and for as variable names. Browsers recognize them as different code items, and so you'll get errors.

Note: You can find a fairly complete list of reserved keywords to avoid at Lexical grammar – keywords.

Good name examples:

age
myAge
init
initialColor
finalOutputValue
audio1
audio2

Bad name examples:

1
a
_12
myage
MYAGE
var
Document
skjfndskjfnbdskjfb
thisisareallylongstupidvariablenameman

Try creating a few more variables now, with the above guidance in mind.