What is a Variable?

A JavaScript program needs to use values, and that is where variables come into play. A program stores data in variables and assigns a name to refer to them in your program. In this section, we'll look at how to "declare", "initialize", and "update" variables in JavaScript.

After reading this section, consider these questions: 

  • How would programs be written without variables?
  • What is the difference between "declaring" and "initializing" a variable?

Initializing a variable

Once you've declared a variable, you can initialize it with a value. You do this by typing the variable name, followed by an equals sign (=), followed by the value you want to give it. For example:

myName = 'Chris';
myAge = 37;

Try going back to the console now and typing in these lines. You should see the value you've assigned to the variable returned in the console to confirm it, in each case. Again, you can return your variable values by typing their name into the console – try these again:

myName;
myAge;

You can declare and initialize a variable at the same time, like this:

let myDog = 'Rover'; 

This is probably what you'll do most of the time, as it is quicker than doing the two actions on two separate lines.