Essential JavaScript

Going Further

Variables Summary

Let's revisit the three keywords we can use to declare variables: var, let, and const.


varletconst
Variable can be re-assigned?yesyesno
Variable is limited to the block where it was defined?noyesyes

Both let and const have advantages over var, but var has no advantage over either of them.

We use let to define variables that will change. For example, if we plan to do math on a variable, we should use let so we can change its value.

We use const to define variables that won't change. This helps keep our code safe because if we accidentally try to change the value, JavaScript will throw an error to show us our mistake. It is better to discover mistakes early so we can fix them as soon as possible.

Both let and const create variables that can only be accessed within the block where they were defined.

Summary

The general rule is to use const whenever you can, but if you need to change the variable use let instead.

Since we have let and const, we don't have a good reason to use the var keyword anymore.

Learning Goals

  • I can use let and const to declare variables

  • I know when to use let and when to use const

  • I can improve code by changing var to let and const

Code Editor

Click "Run Code" to execute your JavaScript in a secure sandbox and see the output below.

Console Output

// Console output will appear here...

0 output lines