Tuesday, September 11, 2018

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

let var, Const keywords are used to declared variables in typescript and javascript. Variables can be declared globally or locally.
Typescript let, var, Const keyword with examples | Javascript | ES6

Var keyword

the var keyword is for a variable declaration of javascript. Typescript behavior also 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 var keyword  for declaring a variable, It assumes global variables
  3. the variable is redeclared with var keyword, It will not lose its original value
  4. variable returned undefined without declaring and initialization its value

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();

Let Keyword 

 Let keyword introduced ES6 - ES2015, It is used to declare a variable in block scope let keyword with colon defines type annotations
Here is an example of let keyword.
let value = "abc";
console.log(value); // abc
if (true) {
    let value = "newabc";;
    console.log(value); // newabc
}
console.log(value); // abc
Redeclaring same variable with let in the current context throws SyntaxError - Can not redeclare blocked-scope variable value
let value = "abc";
let value = "newabc";

Let variable hosting

when the variable is used without declaring it throws Uncaught ReferenceError: value is not defined
function myfunction() { 
    console.log(value);
}
myfunction()

const keyword 

const keywords same like let and there is the difference. a variable declared with const must be initialized immediately once const variable declared, It values not changed by reassigning 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 variable without declaring it using let and const has thrown ReferenceError. This is to avoid the programming exceptions and safeguard for debugging variables

Difference between Let and var keyword

Both are used to declare a variable Let create a variable in blocked scope var creates a variable in global scope Difference 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

Related article


EmoticonEmoticon