So let’s ask the user (that’s you) for their surname (check your driving license, or ask a friend).
var surname = prompt('Greetings friend, may I enquire as to your surname?');
A little box will pop-up, asking (very courteously if I may say) for your surname. Type your surname in and hit ‘OK’.
The surname you entered is now saved, and it can be referred to as surname. You can get what you entered back out again by typing surname into the console. You should see your surname appearing back to you underneath! Exciting!
You’ve created a variable.
Think, if you will, of a variable as a shelf with a name so it’s easy to get back to. You’ve named a shelf surname.
You can name a variable anything you like, but it’s best to name it in a way that tells what you’ve stored there. For example, surname is better than mything or s.
When you type a variable name into the console you are asking the browser, which looks after the shelves, to go find the shelf and give what’s on it to you. This is also known as the variable’s value. The value can be almost anything - in surname, you’ve stored some letters, known as a string. You can also store numbers and a myriad other kinds of data.
So, a variable has a name and a value.
They are the way we store data, and you’ll be using them a lot.
There are two parts to creating a variable; declaration and initialization. Once it’s created, you can assign (or set) its value.
Declaration is declaring a variable to exist. To return to the shelf metaphor, it’s like picking an empty shelf in a massive warehouse and putting a name on it.
As above, to declare a variable, use the
var keyword followed by the variable name, like this:
var surname; var age;
Initialization is giving a variable its value for the first time. The value can change later, but it is only initialized once.
You initialize a variable using the equals sign (=). You can read it as “the value of the variable on the left should be the data on the right”:
var name = "Tom";
“Tom” is a string - a collection of letters. A string is surrounded by single or double quote marks.
var age = 20;
20 is just a number - and numbers don’t go in quotes.
As mentioned, you can set a variable’s value as many times as you like. It’s called assignment and it looks very similar to initialization. You again use the equals sign, but there’s no need for the
var keyword because we’ve already declared the variable.
It’s like this, yo:
name = "Andy"; age = 43;
Only do this if you’ve declared the variable using the