Typescript let, var, Const keyword with examples | Javascript | ES6

let, var, and Const keywords use to declare variables in typescript and javascript.

Variables are declared either globally or locally.

typescript Var keyword

the var keyword is for a variable declaration of javascript. Typescript behavior is also the same as the functional scope

  1. Variable declared with this keyword scope is either locally if declared in a function or globally if declared outside
  2. if the variable is not used the var keyword for declaring a variable, assumes global variables
  3. the variable is redeclared with the var keyword, It will not lose its original value
  4. variable returned undefined without declaring and initialization its value

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 ES6 - ES2015. It does declare a variable in block scope let keyword with colon defines type annotations. 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

Redeclaring the same variable with let in the current context throws 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 keywords are the same as let and there is a difference.

a variable declared with const must be initialized immediately once the const variable is declared, Its values are not changed by reassigning a new value Example

const value = 123;
function myfunction() {
  value = 123; // not allowed
}

ES6 Let and Const temporal dead zone

This was introduced in ES6. Calling a variable without declaring it using let and const has thrown ReferenceError.

It is to avoid programming exceptions and safeguard debugging variables.

Difference between Let and var keyword

Both are used to declare a variable Let creates a variable in the blocked scope var creates a variable in the global scope.

The different example is as below.

// example var
for (var val = 0; val < 2; val++) {
  console.log(val);
}
console.log(val); // 5

// example let
for (let val = 0; val < 2; val++) {
  console.log(val);
}
console.log(val); // undefined