const vs let vs var javascript code example

Example 1: let vs const

`const` is a signal that the identifier won't be reassigned.

`let` is a signal that the variable may be reassigned, such as a counter in a
loop, or a value swap in an algorithm.

It also signals that the variable will be used only in the block it's defined
in, which is not always the entire containing function.

Example 2: var let const javascript

Const vs Let vs Var

const pi = 3.14

pi = 1 
cannot do this becuase with const you cannot change the value

_____________________________________


Let --> is block level 

for(let i = 0; i < 3; i++) {
console.log(i) --> it will console here
}
console.log(i) ---> Not here


---------------------------------------

Var is for variables available to the entire function 


for(var j = 0; j < 3; j++) {
console.log(j) --> it will console here
}
console.log(j) ---> it will console here

Example 3: const let var scope

var num = 1;   //var can be function or global scoped
const num = 2; //const can only be block scoped
let num = 3;   //let can only be block scoped

Example 4: var vs let vs const

var: 
	- hoisted (always declared at top of scope, global if none)
    - function scope
let:
    - block scope
    - not redeclarable
const: 
    - block scope
    - not reassignable
    - not redeclarable
    
Note: Although it may seem like these hold only semantic meaning, using the
appropriate keywords helps the JS engines' compiler to decide on what to optimize.

Example 5: 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 6: 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();