JavaScript : var vs let vs const -part 1
ES6 introduced two new important JavaScript keywords namely :let
and const
.These two keywords provide Block Scope in JavaScript.Before ES6, JavaScript had only two types of scope: Global Scope and Function Scope.So let’s see the differences in var, let and const keywords.
var keyword:
var declares a function-scoped or globally-scoped variable.We can redefine and re-declare variables using var keyword like this.
If we try to use the variable before it’s declaration we get the output as undefined because in JavaScript variables and functions are hoisted.(Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution or else we can say that var
declarations, wherever they occur, are processed before any code is executed)
let keyword
let
allows you to declare variables that are limited to the scope of a block statement, or expression on which it is used, unlike thevar
keyword, which defines a variable globally, or locally to an entire function regardless of block scope.
We can’t re-declare variables which are declared using let keyword like in var keyword…but can redefine those.
If we try to use the variables declared by using let keyword before it’s declaration we get an error like this👇…. All variables declared in JavaScript using var,let or const are hoisted …but let and const are not initialized to ‘undefined’ .Thus we can’t use those before decoration.
const keyword
const declaration creates a constant whose scope can be either global or local to the block in which it is declared.It creates a read-only reference to a value. It does not mean the value it holds is immutable—just that the variable identifier cannot be reassigned.(it does NOT define a constant value. It defines a constant reference to a value.)
The value of a constant can’t be changed through reassignment, and it can’t be re-declared.
We can’t use constants before decoration like in var keyword.We get an error like this 👇
You can find the part 2 from here 👇