In JavaScript, we can declare variables using three keywords var, let and const. Let’s see about the scope and difference of these three variable declarations.
All the three keywords are used to declare a variable. var is ES5, where let and const are introduced in ES6.
Variable Declarations
Let’s see what is a variable declaration.
Using var, let and const you can declare varaible.
var x = 10; // variable decalartion
let y = 11;
const z = 100;
What happens if we declare the variable without a value.
var x;
console.log(x); // undefined
let y;
console.log(y); // undefined
const z; // Uncaught SyntaxError: Missing initializer in const declaration
If we want to update the variable value, we don’t need to redeclare it again. We can only update var and let, where const can be updated. If we try to redeclare it, will produce a type error.
- let can be reassigned, but cannot be redeclared in the same scope.
- const cannot be reassigned and cannot be redeclared in the same scope.
- var can be reassigned and redeclared.
x = 15;// reassigning the variable var x
y = 20; // reassigning the variable let y
z = 200; // Uncaught TypeError: Assignment to a constant variable
var x = 20; // when you give assign different values to same varaible browser will accept the latest value when declared in var
let y = 30; // Uncaught SyntaxError: Identifier 'y' has already been declared
Since, we can redeclare the variable in var keyword, for a small number code there won’t be an issue in finding if we redeclare it. But when in large number of lines of code, it will mess up the work. That’s why most of the developers use let and const.
- use let when plan to reassign the value to a variable.
- use const when planned to not reassigning the values to a variable.
Top comments (0)