What is a Variable in JavaScript

Xiao Yang
Altcademy
Published in
3 min readNov 30, 2016

--

A variable is a place to store values in programming. They are like boxes we use to keep objects in. We keep track of our boxes by labelling them. Therefore we must label our variables too. To create a new variable in JavaScript, we need to use the keyword ‘var’ and choose a meaningful name. We can use letters and digits, but we cannot start with a digit. We cannot use punctuation except ‘$’ and ‘_’. We also cannot use keywords and reserved words.

Keywords are words that have a special functionality, such as ‘var’. Reserved words are words that JavaScript would like to keep for future use as keywords. Here is a list of keywords and reserved words.

break case catch class const continue debugger
default delete do else enum export extends false
finally for function if implements import in
instanceof interface let new null package private
protected public return static super switch this
throw true try typeof var void while with yield

Let’s create a variable called ‘favouriteNumber’.

var favouriteNumber;

When a variable is created like this, it’s like creating an empty box. It is not storing anything yet. To put something in our variable, we need to use the operator ‘=’. This looks like the same equal sign we use in arithmetic. But its functionality in JavaScript is to assign values to variables. Let’s assign the number 9 to our ‘favouriteNumber’ variable.

favouriteNumber = 9;

Notice we are not using the keyword ‘var’ here. We only use ‘var’ when we are creating a new variable (making a new box). Right now, our ‘favouriteNumber’ variable is storing the number 9. Just like in real life, we can swap out the values we store in our variables. We do this by simply assigning a new value using the ‘=’ operator. We’ve changed our mind, our favourite number is actually 23.

favouriteNumber = 23;

Remember that the ‘=’ operator in JavaScript means assign, it does not have the same meaning in arithmetic, which is equal. Therefore it allows us to do something crazy. Look at the following line of code.

favouriteNumber = favouriteNumber + 10;

What? How can favouriteNumber be equal to favouriteNumber + 10? This is sorcery! Relax, it’s just programming. When we use the ‘=’ operator, it will first evaluate the expression on the right ( favouriteNumber + 10 ). Then assign the result of that expression to the variable on the left. When the expression ( favouriteNumber + 10 ) is evaluated, ‘favouriteNumber’ still contains the number 23. Which means the result of this expression is 33. ‘favouriteNumber’ is then assigned the number 33.

Finally, when we create a new variable, we can assign a value to it right away in one line of code like this.

var favouriteWord = 'Sorcery';

Thank you for reading the beginner’s guide to JavaScript variables. If you want to learn more, we are teaching an online front-end web development program at Altcademy.

--

--