Variables are containers that store values. You start by declaring a variable with the var or the let keyword, followed by the name you give to the variable:
EXAMPLE:
And here’s what’s happening in the example above:
var is the keyword that tells JavaScript you’re declaring a variable.
x is the name of that variable.
= is the operator that tells JavaScript a value is coming up next.
100 is the value for the variable to store.
Note: A semicolon at the end of a line indicates where a statement ends.
You can name a variable nearly anything, but there are some restrictions:
A JavaScript identifier must start with a letter, underscore (_), or dollar sign ($). Subsequent characters can also be digits (0–9).
Because JavaScript is case sensitive, letters include the characters "A" through "Z" (uppercase) as well as "a" through "z" (lowercase).
EXAMPLE:
And here are some invalid variable names — try to spot what’s wrong with each of them:
EXAMPLE
var total% = 78;
var 2fast2catch = "bold claim";
var function = false;
var class = "easy";
Using variables
After you declare a variable, you can reference it by name elsewhere in your code.
EXAMPLE:
You can even use a variable when declaring other variables.
EXAMPLE:
Reassigning variables
You can give an existing variable a new value at any point after it’s declared.
EXAMPLE:
No comments:
Post a Comment