Variables allow computers to store and manipulate data.
You can think of a variable as a simple and shorter name that we use to represent the data we want to refer to,
kind of like the
y in mathematics.
Computer variables, however, can store not only numbers, but different values at different times.
JavaSript has seven different data types:
Any of the above seven data types can be stored in a variable.
declare a variable by using the magical keyword
var in front of it:
var myName; var myPhoneNumber;
The code above creates two variables:
Notice also how each
statement, a list of instruction that we give to a computer to execute, ends with a
To declare a variable, you can use
_, but not
spaces or make a variable start with a number.
Once we have declared a variable, we can store a value in it thanks to the assignment operator
myPhoneNumber = 17;
Number value 17 is assigned to the variable
Always keep in mind that assignment goes
from right to left.
Everything standing on the right of the
= operator is resolved before the value is assigned to the variable on the left of the operator.
myVar = 17; myNum = myVar;
The code above assigns the
Number 17 to
myVar, then resolves
myVar to 17, and finally assigns the same value to
Although you can declare a variable and subsequently assign a value to it, it is common to initialize a variable to an initial value at the moment when it is declared.
var myNumber = 0;
The code above creates a new variable called
myNumber and assigns it an initial value of
For this reason, if we try to perform any mathematical operation with an
undefined variable, we will get as a result
NaN (“Not a Number”).
var a = 16; var b = 'My name is '; a = a + 1; b = b + ' Enea!'; console.log(a); // 17 console.log(b); // "My name is Enea!"
For instance, if we take into consideration the following three variable names:
myvar, they all represent three different variables.
camelCase. Thus, if we have to deal with a multi-word variable name, we write the first word in
lowercase and the first letter of each subsequent word as
var myPhone; var myPhoneNumber; var myPersonalPhoneNumber;