> var myNumber = 45; undefined > myNumber; 45
myNumber is a variable that we set equal to 45. On the second line, when we type
Sometimes you'll see a variable initially set without the
var keyword, like this:
myNumber = 45;
This works... most of the time, but it can cause really bad bugs down the road. Get in the habit of using the
var keyword whenever you create a new variable, and you'll save yourself some massive headaches later.
You can change the value of a variable:
> var myNumber = 45; undefined > myNumber = 50; 50 > myNumber; 50
You can do arithmetic with your variables:
> var favoriteNumber = 13; undefined > favoriteNumber * 4; 52
Does the variable change when you perform arithmetic on it?
> var favoriteNumber = 7; undefined > favoriteNumber + 1; 8
Nope. But what if we do:
> var favoriteNumber = 6; undefined >favoriteNumber = favoriteNumber + 1; 7
Here’s a shortcut:
favoriteNumber += 1.
You can use more than one variable at a time, too:
> var num1 = 5; undefined > var num2 = 6; undefined > var num3 = num1 + num2; undefined > num3 11
Don't worry for the moment about that
undefined return value. Technically speaking, it says undefined because declaration of a variable first creates a variable without a value - hence undefined - before assigning it the value that comes to the right of the equals (
Variable: Variables can be thought of as containers used to store information. They allow for a way to label data with a descriptive name.
Set a variable equal to a number:
var myNumber = 45;
Use a variable without modifying its value:
favoriteNumber * 4;
Use a variable and modify it:
favoriteNumber = favoriteNumber * 4;
favoriteNumber *= 4;
Use multiple variables:
var myNumber = 45; var otherNumber = 12; myNumber + otherNumber;
Variables should begin with a letter.
Variables are case sensitive (
myNumber is a different variable than
Use clear names that describe the value being stored like
Always name your variables in a manner that will be easy for other developers to understand. Avoid vague letters or initials. (For example:
var x = 45 doesn't tell us what the value is. Is 45 an age, a distance, size, a time?...)