Variable in JavaScript – Explained with Examples
A JavaScript variable is a container used to store JavaScript data (values).
Let’s see a variable’s syntax.
Syntax
In the snippet above is an uninitialized variable. You can initialize JavaScript variables with this syntax:
Below are some examples.
Example 1: Generic Variable
The code in the snippet above is a generic variable named anyWord
. It is generic (not a JavaScript variable) because we defined it without any JavaScript keyword.
Example 2: Initialized Generic Variable
In the snippet above, we initialized the generic variable (anyWord
) with a concatenation of "Val1"
and "Val2"
.
Example 3: JavaScript Variable
In the snippet above, we used the keyword var
to declare the creation of a JavaScript variable named anyWord
.
Example 4: Initialized JavaScript Variable
In the snippet above, we initialized the JavaScript variable (anyWord
) with a concatenation of "Val1"
and "Val2"
.
The computer will analyze anyWord
as a JavaScript variable because we used the var
keyword to declare it so.
Note that the var
keyword is one of JavaScript’s variable keywords.
But what is a JavaScript variable keyword? Let’s find out.
What Is a JavaScript Variable Keyword?
A JavaScript variable keyword is a code used to declare that a specific variable is a JavaScript variable—not a mathematical or generic variable.
The three types of JavaScript variable keywords are:
var
let
const
Let’s discuss the differences between the three keywords.
Var vs. Let vs. Const – What’s the Difference?
Below are the main differences between JavaScript’s var
, let
, and const
variable keywords.
Hoisting – How does JavaScript hoisting work with var
, let
, and const
variables?
When a var
variable gets hoisted, JavaScript automatically assigns it the undefined
value.
However, when the computer hoists a let
or const
variable, JavaScript puts it in a “Temporal dead zone”—until the variable gets fully initialized.
For instance, consider this code:
The snippet above returned undefined
because JavaScript automatically assigned the value undefined
to the variable immediately after hoisting var bestColor
.
Let’s now see what will happen if we substitute var
with the let
keyword.
The snippet above returned ReferenceError
because immediately after hoisting let bestColor
, JavaScript made the variable inaccessible.
So, what do you think would happen if we substitute let
with the const
keyword? Let’s find out below.
The snippet above returned ReferenceError
because immediately after hoisting const bestColor
, JavaScript made the variable inaccessible.
Scope – What is the scope of a var
, let
, or const
variable?
A var
variable is function scoped. So, when defined in a function, only the function’s code would have access to it.
let
and const
variables are block scoped. So, they are accessible only within their block ({...}
).
Example: Blocks do not constrain var variables
Notice that console.log
called the color
variable from outside the if
statement’s block.
console.log
gained access to the color
variable’s value because var
variables do not get constrained by anything—but functions.
In other words, since var
is function scoped, only a function can prevent an external code from accessing its value.
Example: Var variable is function scoped
The snippet above returned a ReferenceError
because the function statement prevents all external code from accessing the var
variable. Instead, only the function’s local code can access the var
variable.
Note that if you defined a var
variable locally and globally. In that case, the local version will take precedence.
Here’s an example:
Keep in mind that any var
variable you defined outside a function will be in the global scope. Therefore, such variable is known, visible, and accessible globally to all code.
Create your web presence in no time
Example: Var variables that are not in any function are in the global scope
The console.log
code gained access to colorOutsideFunc
because any var
variable defined outside a function is globally available to all code.
Let’s now see how scope works with a let
variable.
The snippet above returned a ReferenceError
because the block ({...}
) prevents all external code from accessing the let
variable. Instead, only the block’s local code can access the let
variable.
So, suppose you move the console.log
code into the if
statement’s block. In that case, console.log
will have access to the color
variable.
Here’s an example:
Let’s now see an example of a const
variable.
The snippet above returned a ReferenceError
because const
is block scope. Therefore, the block ({...}
) prevents all external code from accessing the const
variable. Instead, only the block’s local code can access the const
variable.
Keep in mind that any let
or const
variable you defined outside a block will be in the global scope. Therefore, such variable is known, visible, and accessible globally to all code in the same script.
Example: Const (or let) variables not in any block are in the global scope
The console.log
code gained access to colorOutsideFunc
because any let
or const
variable defined outside a block is globally available to all code within the same script.
Let’s now discuss the difference between var
, let
, and const
declarations.
Declaration – Can you declare a var
, let
, or const
variable without assigning it a value?
You can declare a var
or let
variable without assigning it a value.
However, you must initialize a const
variable with an initial value while declaring it. Otherwise, the computer will throw a SyntaxError
.
For instance, consider this snippet:
Notice that the snippet above worked correctly—even though we declared the var
variable without assigning it an initial value.
Let’s now substitute the var
keyword with let
to see what will happen.
Observe that the snippet above also worked correctly.
Let’s now find out what will happen if you declare a const
variable without an initial value.
The snippet above threw a SyntaxError
because you cannot declare a const
variable without assigning it an initial value.
Create your web presence in no time
Name redeclaration – Can you redeclare the name of a var
, let
, or const
variable?
You can redeclare the name of a var
variable. However, you are not allowed to redeclare the name of let
and const
variables.
For instance, the redeclaration of the color
variable in the snippet below will work.
However, the redeclaration below will fail because you cannot redeclare the name of a let
or const
variable.
Also, note that the snippet below will fail because a variable named bestPet
already exists in the script.
Value reassignment – Can you reassign the value of a var
, let
, or const
variable?
You can reassign the value of a var
or let
variable. However, you are not allowed to reassign the value of a const
variable.
For instance, the reassignment of the color
variable below will work.
Likewise, the reassignment below will also run without any error.
However, the reassignment below will fail because you cannot reassign the values of a const
variable.
Keep in mind that you can update the values of any object—even if the object is in a const
variable.
Here’s an example:
Window object – How does a var
, let
, or const
variable work with the window
object?
Suppose you declare a var
variable in the global scope (out of a function). In that case, the computer will include it as one of the properties of the window
object.
As such, the variable will be accessible globally by any code that can access the window
object—which makes var
vulnerable to any third-party intrusion.
However, suppose you declare a let
or const
variable in the global scope (out of a block). In such a case, the computer will not add it to the window
object.
Therefore, the variable will only be available globally within its script file—not generally to any code that can access the window
object.
Learn CSS Grid with Images
Example: Global var
variables become part of the window
object—let
and const
do not
Notice that we were able to invoke colorsArray
from the window
object. The invocation worked because colorsArray
is a var
variable that we defined in the global scope.
Let’s now substitute var
with the let
keyword to see what will happen.
Observe that the snippet above returned undefined
because the computer would not include a let
or const
variable as a property of the window
object.
Keep in mind that any function declared in the global scope will become one of the properties of the window
object.
Therefore, suppose you define your variable in a globally scoped function. In such a case, the variable could be executable by any code that can access the window
object—regardless of whether the variable is var
, let
, or const
.
Example: Global functions become part of the window
object
Notice that we were able to invoke colorsArray
from the window
object through the globally scoped getColor
function.
Suppose you wish to prevent global access to your function’s local code. In such a case, define that function in a const
or let
variable like so:
Observe that the snippet above returned a TypeError
. The error is because the computer does not include const
variables as one of the properties of the window
object.
However, you can execute the function from your script successfully like so:
Variable naming – How to name a var
, let
, or const
variable
A standard convention for naming const
variables is to use all-uppercase letterings.
Here’s an example:
Apart from the const
convention stated above, all your variable names should conform to these general guidelines:
- Variable names must start only with a letter, dollar sign (
$
), or an underscore (_
).
- Names can contain uppercase or lowercase letterings. However, use only Latin characters (a-z, A-Z, 0-9). By so doing, your variable name will be easy for most developers to understand.
- Variable names are case-sensitive. Therefore,
game
andGame
are different variables. - You cannot use JavaScript reserved keywords as a variable name.
Which is the best – var
, let
, or const
?
A good coding habit is to minimize mutable states.
In other words, it’s best to minimize random alterations of your variables.
Therefore, const
is the recommended declaration keyword for your variables—as it is the only one that prevents variable reassignments.
However, suppose you need to permit the reassignment of your variable. In such a case, use let
.
Generally, it’s best to avoid var
as it makes your variable highly mutable—which can expose your program to third-party intrusions.