Typescript let, var, Const keyword with examples | Javascript | ES6
- Admin
- Mar 6, 2024
- Es6 Javascript Typescript
In TypeScript and JavaScript, variables can be declared using the let, var, and const keywords, each with its own characteristics and scope.
Variables are declared either globally or locally.
typescript Var keyword
The var keyword is inherited from JavaScript and behaves similarly in TypeScript:
- Variables declared with
varhave functional scope, either locally within a function or globally if declared outside. - If a variable is not declared with
var, it is assumed to be global. - Redeclaring a variable with
vardoes not overwrite its original value. - Variables declared with
varare initialized withundefinedif not explicitly assigned.
typescript Var example and usage
var value = 11;
var value1;
function myFunction() {
value = 456; // Allowed
value2 = 14;
console.log(value); // 456
console.log(value1); // undefined
console.log(value2); // 14
}
myFunction();
TypeScript let Keyword
The let keyword, introduced in ES6 (ES2015), declares variables with block scope.
Here is an example of the let keyword.
let value = "abc";
console.log(value); // abc
if (true) {
let value = "newabc";
console.log(value); // newabc
}
console.log(value); // abc
Attempting to redeclare the same variable within the same block context using let results in a SyntaxError Can not redeclare blocked-scope variable value.
let value = "abc";
let value = "newabc";
typescript Let variable hosting
when the variable used without declaring it throws Uncaught ReferenceError: value is not defined
function myfunction() {
console.log(value);
}
myfunction();
TypeScript const Keyword
const is similar to let, but variables declared with const must be initialized immediately and cannot be reassigned:
In this, Its values are not changed by reassigning a new value.
const value = 123;
function myFunction() {
value = 123; // Not allowed
}
ES6 let and const Temporal Dead Zone
In ES6, accessing a variable declared with let or const before its declaration results in a ReferenceError, preventing potential programming errors.
It is to avoid programming exceptions and safeguard debugging variables.
Difference Between let and var
Both let and var are used for variable declaration, but they differ in scope:
Let creates a variable in the blocked scope var creates a variable in the global scope.
The different example is as below.
// Example with var
for (var val = 0; val < 2; val++) {
console.log(val);
}
console.log(val); // 2
// Example with let
for (let val = 0; val < 2; val++) {
console.log(val);
}
console.log(val); // Error: val is not defined
Summary
In summary, let creates variables with block scope, while var creates variables with functional scope. Understanding these differences is crucial for writing robust and error-free code in TypeScript and JavaScript.
