<New code>
//INIT:
var exampleStringVariable = "red";
— assigns the string "red" to exampleStringVariable
`
document.getElementById( 'exampleId' ).style.backgroundColor
= exampleStringVariable;
— makes the element called
exampleId have a red background
//INIT:
var exampleNumericVariable = 5;
— assigns 5 to exampleNumericVariable
//INIT:
var exampleStringVariable
= exampleStringVariable + 10;
— adds 10 to exampleStringVariable, making it 15
Creating a variable in Javascript
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.
Technically, you don't have to declare variables in Javascript, but it will help you avoid problems later on with something called variable scope, and most other languages require variable declarations.
So start using var
now!
You only have to declare a variable the first time you use it.
Declaring a variable twice will erase it.
Equals (=
) 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."
Common problems
- 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?
Learn more
- Khan Academy's Intro to variables
- w3schools.com's JavaScript Variables