JavaScript: Variables
Last updated
Last updated
Variables are used to store this information.
A variable is a “named storage” for data. We can use variables to store goodies, visitors, and other data.
To create a variable in JavaScript, use the let
keyword.
We can put any value in the box.
We can also change it as many times as we want:
When the value is changed, the old data is removed from the variable:
We can also declare two variables and copy data from one into the other.
There are two limitations on variable names in JavaScript:
The name must contain only letters, digits, or the symbols $
and _
.
The first character must not be a digit.
Case matters
Variables named apple
and AppLE
are two different variables.
Non-Latin letters are allowed, but not recommended
It is possible to use any language, including cyrillic letters or even hieroglyphs, like this:
Constants: to declare a constant (unchanging) variable, use const
instead of let
:
We can declare variables to store data by using the var
, let
, or const
keywords.
let
– is a modern variable declaration. The code must be in strict mode to use let
in Chrome (V8).
var
– is an old-school variable declaration. Normally we don’t use it at all, but we’ll cover subtle differences from let
in the chapter The old "var", just in case you need them.
const
– is like let
, but the value of the variable can’t be changed.
Variables should be named in a way that allows us to easily understand what’s inside them.