javascript var vs const vs let code example

Example 1: difference between var let and const in javascript with example

//functional scope 
 var a; // declaration
 a=10; // initialization; 
//global scope
// re-initialization possible
 let a;//only blocked scope & re-initialization possible
 a=10;
let a =20;
if(true){
  let b =30;
}
console.log(b); // b is not defined
const // const also blocked scope,Re-initialization and re-declaration not possible
const a; // throws error {when we declaring the value we should assign the value.
const a =20;
if(true){
  const b =30;
}
console.log(b); // b is not defined
console.log(a); // no output here because code execution break at leve b.

Example 2: var vs let vs const typescript

let num1:number = 1; 
    
function letDeclaration() { 
    let num2:number = 2; 

    if (num2 > num1) { 
        let num3: number = 3;
        num3++; 
    } 

    while(num1 < num2) { 
        let num4: number = 4;
        num1++;
    }

    console.log(num1); //OK
    console.log(num2); //OK 
    console.log(num3); //Compiler Error: Cannot find name 'num3'
    console.log(num4); //Compiler Error: Cannot find name 'num4'
}

letDeclaration();

Tags:

Misc Example