JavaScript uses many different keywords for multiple purposes. As discussed in our previous tutorial, we can use three keywords to declare a variable in JavaScript. Each variable has its own characteristics and functions. Lets demonstrate how we can differentiate between keywords that declare variables.
var keyword | let keyword | const keyword |
---|---|---|
You can redeclare it | You can redeclare it | You cannot redeclare it |
You can reassign it with any value | You can reassign it with any value | You cannot reassign it with a value |
It has both local global and function scope | It has a block scope | It has a block scope |
You can declare it on top and then use it anywhere | You should declare and also initialize it before using | You should declare and also initialize it before using |
You can redeclare them anywhere in the program | You can redeclare them anywhere inside a block | You cannot redeclare |
Declaration
When you declare a variable, we consider multiple factors. If you need to redeclare a variable, its recommended to use var
and let
keywords. For example.
var a = 5;
let b = 5;
if (true) {
var a = 8;
let b = 8;
}
You can redeclare the same variable, i.e. a or b again anywhere in the program using let
or var
. This is not permitted using const
, as it must hold a constant value.
However, the let keyword is preferred to be redeclared inside the same block it is defined, as outside that block it may change value due to its block scope.
Assign and Reassign Values
When we declare a variable, we may at times initialize it or not. When working with let
and const
, it is compulsory to also assign the variable with a value. Keywords declared with let and const should always be initialized before they are being used. For example.
const a = 5;
let b;
console.log(a) // shows 5
console.log(b) // throws an error as not initialized
The value of a stays the same throughout the program, we cannot reassign it with another value. b with let
keyword can be reassigned anywhere throughout the program.
Scope
The scope defines where the variable is used in a program. var
with both global and local scope can be declared and used anywhere. However, const
and let
have blocked and confined scope. To see more explanation on scopes, refer to the tutorial on scope of a variable.