JavaScript variables
Variables store values (data) to make the data more compact and portable for different parts of a JavaScript program. Instead of using the data as-is, we can store them in variables and call them by their variable names. They are like the "pronouns" of programming languages.
JavaScript statements take on a form similar to a mathematical equation (a variable gets a value), but in a manner similar to an assignment (see the second line):
let x = 2
x = x + 1 // 3
In the example above, we do not mean that x
is equal to x+1
(which makes no sense) but that:
"x will have a value of the last known value of x (i.e. 2); x will then add 1 to itself to make 3!"
Alternatively, we can think of the single =
sign as a left-facing arrow:
x <- 2
x <- x + 1
"let x be 2, then let x be 2 + 1"
If only we could rewrite the programming language!
A note about line-ending semi-colons
In Javascript versions after 2015, semi-colons (;
), at the end of each line of JavaScript code, have become optional:
- some programmers prefer to continue to use them out of habit
- others just want to keep their code a little cleaner
Either way, the code will work. Note that this optionality does not include semi-colons in non-line-ending places (which we will see later)!