var exampleStringVariable = "red";
— assigns the string "red" to exampleStringVariable
document.getElementById( 'exampleId' ).style.backgroundColor
— makes the element called exampleId have a red background
var exampleNumericVariable = 5;
— assigns 5 to exampleNumericVariable
= exampleStringVariable + 10;
— adds 10 to exampleStringVariable, making it 15
When you use a variable for the first time in a program, you should declare it first. For example:
var exampleVar = "Hello variables!";
In the example above, the word
var indicates to the program
that exampleVar is the name of a variable and that it can behind
used to store data.
So start using
You only have to declare a variable the first time you use it.
Declaring a variable twice will erase it.
=) works very differently in math and programming
Math is so beautiful!
In math, one side of an equation is always exactly equal to the other side, and you can use this information to solve problems:
- 4x + 24 = 2x - 12
- 2x + 24 = -12
- 2x = -36
- x = -18
But in programming, the equals symbol is used to assign things instead of for equality.
This leads to mathematically obscene lines of code, like this:
playerScore = playerScore + 1;
In math, this reduces to 0 = 1, which is just plain wrong!
In programming, that line of code means: "Take the value of playerScore, add one to it, and then store the result back into playerScore."
- Declare variables when you first use them or odd things may happen
- Declaring a variable a second time will erase it's first value
- Remember that the variable on the left of the equals is stuffed with the code on the right
Test your knowledge
Answer the following questions:
var characterLevel = 10;
characterLevel = characterLevel + 1;
- What is characterLevel now?
var popUpMessage = "Nothing to see here!";
alert( popUpMessage );
- What will appear in the pop up alert?
var numberAlisonsKittens = 3;
var numberOfDavesKittens = numberOfAlisonsKittens + 2;
- What is the value of numberOfAlisonsKittens?
- What is the value of numberOfDavesKittens?
var myCollegeNickname = "The God of Awesome Hair";
myCollegeNickname = "Twerp";
- What is the value of myCollegeNickname?
var numberOfTraps = 10;
numberOfTraps + 1 = numberOfTraps;
- What is numberOfTraps now?