- one of the most important concepts in programming
- a way of storing and keeping track of information in a program, so that it can be later used, and manipulated.
- score is an example of a variable
var score; /* Declaring a variable */ var score = 0; /* Assigning a value to a variable */
Declaring a Variable
var message = "Hello!"; console.log(message);
In this program, the word “message” is now a reference to the value “Hello!”, so whenever I use “message” in the program, as long as I don’t change its value, it will always mean, “Hello!”.
Reassigning the Variable
We don’t use
var again to reassign a variable, it’s only used when we first create or declare a variable.
- Names can’t start with a number.
- Names can only contain letters, numbers, and the
- Capitalizing every word following the first is called camel case by programmers
Changing the Value in a Variable
var score = 0 score = score + 10;
- When putting a value into a variable, whatever’s to the right of the equal sign goes into the variable on the left.
- In this case above, what’s the right is the current contents of the variable score + 10.
var score = 0 score += 10; /* addition assignment operator - addition to its current value */ /* this adds a value 10 to the current value of the score */ var bonusPts = 100; var finalScore = score + bonusPts; console.log(finalScore); /* We are adding the current value of the variable score plus the value of the variable bonusPts and saving the sum of those values to the third variable, finalScore */
const – constant, the value of the variable can’t change. We cannot change nor manipulate the value of a constant through reassignment. We also cannot redeclare a constant.
let – for variables whose value should change while the program runs.
let won’t let you override an assignment, while
var would let you reassign a variable
- Addition (
+) – MDN