//INIT: Using variables

<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:

  1. 3x + 24 = 2x - 12
  2. 2x + 24 = -12
  3. 2x = -36
  4. 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

Test your knowledge

Answer the following questions:

Learn more