Javascript var, let, const difference
Ajay Baraiya
Posted on September 3, 2022
Remember three points to distinguish var, let, const.
- Declaration - Can we redeclare it in same code?
- Block Scope - Can value be set up only to block? or it acts like global?
- Can we reassign value? or can this be declared without value and than after assign value?
By below example we can understand all above points very well.
Note: If you don't know what is scope in Javascript just google it :)
var x=9; //Declared 1st time
var x=10; //Declared 2nd time: Allowed here
let v=9; //Declared 1st time
let v=2; //Declared 2nd time: Not allowed as both in same scope (comment down this line and execute in browser console).
const PI; //Declared 1st time without value assign: Not allowed as const needs value assigned at the time of declaration (comment down this line and execute in browser console).
const PI=3.14; //Declared 2nd time: Allwed as it is proper declaration.
PI=3.14159; //Reassign const value: Not allowed (comment down this line and execute in browser console).
function BlockScope(){
console.log('----------block space start-----------');
var x=2; //Declared 3rd time: Allowed here
console.log(x); //x will be 2 over here
let v=3; // Declared 3rd time: Allowed as scope is changed here.
console.log(v); //v will be 3 over here
const PI=3.1415; //Declared 3rd time: allowed as it follow Scope Principle.
console.log(PI); //PI will be 3.1415
console.log('----------block space end-----------');
}
BlockScope();
console.log(x); //x will be 2 which do not follow block scope (means var do not follow scope principle).
console.log(v); // v will be 9 here (means let follow scope principle).
console.log(PI); // PI will be 3.14 and not 3.1415 as it follow scope principle.
v=12; //allowed and value will be chagned to 12 when you run(3rd point)
💖 💪 🙅 🚩
Ajay Baraiya
Posted on September 3, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
javascript Building an Awesome Carousel Reusable Component with React and Splide.js
November 7, 2022