Here’s how to declare a variable:
var x = 100;
And here’s what’s happening in the example above:
xis the name of that variable.
100is the value for the variable to store.
After you declare a variable, you can reference it by name elsewhere in your code.
var x = 100; x + 102;
You can even use a variable when declaring other variables.
var x = 100; var y = x + 102; y;
You can give an existing variable a new value at any point after it’s declared.
var weather = "rainy"; weather = "sunny"; weather;
Variable names are pretty flexible as long as you follow a few rules:
- Start them with a letter, underscore
_, or dollar sign
- After the first letter, you can use numbers, as well as letters, underscores, or dollar signs.
With that in mind, here are valid variable names:
var camelCase = "lowercase word, then uppercase"; var dinner2Go = "pizza"; var I_AM_HUNGRY = true; var _Hello_ = "what a nice greeting" var $_$ = "money eyes";
And here are some invalid variable names — try to spot what’s wrong with each of them:
var total% = 78; var 2fast2catch = "bold claim"; var function = false; var class = "easy";
Variable names are case-sensitive, so
myvar are all different variables. But generally, it’s a good practice to avoid naming variables so similarly.