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:
1var myName;2var 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.
Storing Values with the Assignment Operator
Once we have declared a variable, we can store a value in it thanks to the assignment operator
1myPhoneNumber = 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.
1myVar = 17;2myNum = myVar;
The code above assigns the
Number 17 to
myVar, then resolves
myVar to 17, and finally assigns the same value to
Initializing Variables with the Assignment Operator
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.
1var myNumber = 0;
The code above creates a new variable called
myNumber and assigns it an initial value of
Understanding Uninitialized Variables
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").
1var a = 16;2var b = 'My name is ';34a = a + 1;5b = b + ' Enea!';67console.log(a); // 178console.log(b); // "My name is Enea!"
Understanding Case Sensitivity in Variables
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
1var myPhone;2var myPhoneNumber;3var myPersonalPhoneNumber;