Javascript var, let, const difference

ajaybaraiya6

Ajay Baraiya

Posted on September 3, 2022

Javascript var, let, const difference

Remember three points to distinguish var, let, const.

  1. Declaration - Can we redeclare it in same code?
  2. Block Scope - Can value be set up only to block? or it acts like global?
  3. 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) 


Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
ajaybaraiya6
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

Dark Mode Guy
javascript Dark Mode Guy

April 20, 2023

Infinite-Scroll And GitHub REST API
javascript Infinite-Scroll And GitHub REST API

November 22, 2022

Keeping tabs on Bitcoin
javascript Keeping tabs on Bitcoin

November 12, 2022

Javascript var, let, const difference
javascript Javascript var, let, const difference

September 3, 2022