Note: You will usually see
const
andlet
when using variables. However, you will see legacy code that usesvar
to declare variables. DO NOT DO THIS, it is uneccessary in modern JavaScript.
A variable is a container for some value, usually one we want to re-use.
Consider this plain english example:
My name is Clark Kent.
name
is the variable (our container)
Clark Kent
is the value we are putting inside the container
In JavaScript (JS), we would write this as
const name = 'Clark Kent';
const
tells the machine we are declaring a constant variable i.e. a variable that will not change its value.
name
tells the machine what we will refer to the container as.
=
tells the machine we want to assign the value on the right side to the variable on the left side.
'Clark Kent'
is a String value, the machine knows this because the characters Clark Kent
are wrapped in quotation marks.
Because this is a constant value, we cannot reassign the variable i.e. we cannot put a different value in our constant container.
const name = 'Clark Kent';
name = 'Bruce Wayne';
// => Error
You cannot redeclare the same variable twice. This will cause an error.
const name = 'Clark Kent';
const name = 'Bruce Wayne';
// => Error
Most of the time, we want to use constant variables to avoid collisions or prevent our values from being altered unexpectedly. This is a good practice.
However, there will be a limited number of times where you may want to declare a variable without assigning it a value. This will usually happen when you are working with external information (like a database).
Variables we can change are declared with let
. You can assign a value immediately or later on after doing other things. Here is a fake example.
// declare the variable
let name;
// assign a value to our container
name = 'Clark Kent';
let
tells the machine we are going to declare a variable that is not constant.
It is important that we only try to assign variables we have already declared.
name = 'Bruce Wayne';
// => Error because we didn't declare `name`
-
Assign your name to a constant variable.
-
Try to cause an error by reassigning a different value to your variable.
-
Declare one of your parent's names as a variable that is not constant. Now change the value of your variable without causing an error.
-
Try to cause an error by assigning a pet's name to a variable you have not declared.
Note. You can open the developer console in your web browser to run these exercises. If you want to print out your variables, you can use
console.log
, for example:const name = 'Clark Kent'; console.log(name);