Variables
The keyword
var
is used in pre-ES6 versions of JavaScript.In programming, a variable is a container for a value. You can think of variables as little containers for information that live in a computer’s memory. Information stored in variables, such as a username, account number, or even personalized greeting can then be found in memory.
Variables also provide a way of labeling data with a descriptive name, so our programs can be understood more clearly by the reader and ourselves.
General rules for naming variables:
Variable names cannot start with numbers
Variable names are case sensitive, so
myName
andmyname
would be different variables.Variable names cannot be the same as keywords. For a comprehensive list of keywords check out MDN's keyword documentation.
Variable names should follow Camel Casing format .e.g.
myLastVariable
(the first word of the variable is always in lowercase and all the following words will be always be in uppercase).Assingment operator
=
is used to assign certain data type to the variable name.
Creating a variable: var
A lot of changes were introduced in the ES6 version of JavaScript in 2015, like
let
andconst
, to create or declare, variables.Prior to ES6 only
var
keyword could be used to declare variables.
Creating a variable: let
let
keyword was introduced in ES6 in 2015, it signals that the variable can be reassigned a different value.
Example:
When using
let
we can declare a variable without assigning the variable a value.In such cases the value is automatically initialized with a value of
undefined
.
Example:
All variables declared with keyword
let
can be reassigned with new values.
Creating a variable: const
const
keyword was also introduced in the ES6 version of JavaScript in 2015Just like
var
andlet
we can useconst
to store any value in a variable
Example:
A
const
variable cannot be reassigned because it is a constant, if tried so will throw an errorTypeError
Example:
Last updated