A variable allows you to store some value in a easy to remember name so that you can retrive the stored value.
For instance if I wanted to make a program that dealt with money, then having a variable called 'balance' is easier than constantly writting out my current balance in numbers. This also gives us the advantage of updating the variable in one location, and having it update everywhere.
Consider the following:
// My balance is 10.00
// Increment balance by 5.00
10.00 + 5.00
// Remove 7.23 from balance
15.00 - 7.23
What is my balance?
var balance = 10.00;
balance = balance + 5.00;
balance = balance - 7.23;
console.log(balance)
As you can see you specify a variable with the var
keyword. You can also now use the let
keyword and this is preffered in modern JavaScript.
You can use symbol shortcus to do maths on variables.
CODE | EXPLAINATION |
---|---|
x++ |
increment the variable x by 1 |
x += y |
increment the variable x by amount y |
x -= y |
decrement the variable x by amount y |
x-- |
decrement the variable x by amount y |
x *= y |
multiply the variable x by amount y |
x /= y |
divide the variable x by amount y |
x %= y |
modulo the variable x by amount y |