In JavaScript, variables are used to store data values that can be used and manipulated throughout the code. Variables in JavaScript can hold different types of data, such as numbers, strings, boolean values, arrays, objects, and functions.
There are three keywords used to declare variables -
var
, let
, and const
.
The syntax to create a variable is first the keyword, a space, the name we are giving the variable, an equal sign, the value we are assigning the variable, and then a semicolon.
var firstName = 'Salvador'; let lastName = 'Dali'; const favouritePet = 'Babou';
Variables declared with var
have function scope, which means
they are accessible throughout the function in which they are declared.
Variables declared with let
and const
have block
scope, which means they are only accessible within the block in which they
are declared.
In JavaScript, variables can also be re-assigned new values using the
assignment operator =
.
It's important to note that const
variables cannot be
re-assigned, and attempting to do so will result in a syntax error.
Additionally, all variables in JavaScript are hoisted to the top of their
scope, which means that they are declared before any code is executed.
This can sometimes lead to unexpected behavior, so it's important to
understand how hoisting works in JavaScript.
var
is the ES5 way of declaring a variable. This is a generic
variable keyword. Variables created with var can be changed without
causing errors.
const
is a variable that cannot be changed later in the code.
let
is a new ES6 variable keyword. This will assign a
variable much like var, but with a little bit different behavior. Most
notably, it differs by creating "block level scope".
var
can be re-assigned and changedlet
can be re-assigned but not changedconst
cannot be re-assigned nor changed