Variables
Variables are containers that store values. You start by declaring a variable with the var (less recommended, dive deeper for the explanation) or the let keyword, followed by the name you give to the variable:
Empowering Today’s Learners to Become Tomorrow’s Leaders
Variables are containers that store values. You start by declaring a variable with the var (less recommended, dive deeper for the explanation) or the let keyword, followed by the name you give to the variable:
let myVariable;
Note: A semicolon at the end of a line indicates where a statement ends. It is only required when you need to separate statements on a single line. However, some people believe it's good practice to have semicolons at the end of each statement. There are other rules for when you should and shouldn't use semicolons. For more details, see Your Guide to Semicolons in JavaScript.
Note: You can name a variable nearly anything, but there are some restrictions. (See this section about naming rules.) If you are unsure, you can check your variable name to see if it's valid.
Note: JavaScript is case sensitive. This means myVariable is not the same as myvariable. If you have problems in your code, check the case!
Note: For more details about the difference between var and let, see The difference between var and let.
After declaring a variable, you can give it a value:
myVariable = 'Bob';
Also, you can do both these operations on the same line:
let myVariable = 'Bob';
You retrieve the value by calling the variable name:
myVariable;
After assigning a value to a variable, you can change it later in the code:
let myVariable = 'Bob';
myVariable = 'Steve';
Note that variables may hold values that have different data types:
So why do we need variables? Variables are necessary to do anything interesting in programming. If values couldn't change, then you couldn't do anything dynamic, like personalize a greeting message or change an image displayed in an image gallery.