Thursday, September 21, 2023

Interview Question Difference between let vs var & const in Type Script (Part 7)

 Advantages of using let over var

We cannot read or write before they are declared , if the variable is declared as let .Whereas it won't give an error when using variables before declaring them using var.

console.log(num1);
let num1:number = 10 ;

console.log(num2);
var num2:number = 10 ;

Output



variables declared with let cannot be re-declared

The TypeScript compiler will give an error when variables with the same name (case sensitive) are declared multiple times in the same block using let.

Whereas it wont give any error when declaring variable with var.

var num:number = 02; // OK
var Num:number = 22;// OK
var NUM:number = 34;// OK
var NuM:number = 444;// OK

let num:number = 52;// Compiler Error: Cannot redeclared block-scoped variable 'num'
let Num:number = 66;// Compiler Error: Cannot redeclared block-scoped variable 'Num'
let NUM:number = 77;// Compiler Error: Cannot redeclared block-scoped variable 'NUM'
let NuM:number = 88;// Compiler Error: Cannot redeclared block-scoped variable 'NuM'
Note:
Variables with the same name and case can be declared in different blocks using let.

const
Variables can be declared using const as well. If declared const it values cannot be changed

const num:number = 100;
num = 200; //Compiler Error: Cannot assign to 'num' because it is a constant or read-only property

Const variables must be declared and initialized in a single statement. Separate declaration and initialization is not supported.

const num:number; //Compiler Error: const declaration must be initialized
num = 100; 

No comments:

Post a Comment

Thank you for visiting my blog

Kubernetes

Prerequisites We assume anyone who wants to understand Kubernetes should have an understating of how the Docker works, how the Docker images...