Wednesday, July 31, 2019

Difference between var, let, const in Javascript

From ES6 we have three ways to declare a variables
var a = 48;
const b = 'Hello Shaik';
let c = true;
The type of declaration depends on the scope. The scope is the fundamental concept in all programming languages that defines the visibility of a variable.

Var

 The var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.

Ex:
function testVar() {
  var x = 1;
  if (true) {
    var x = 2;  // same variable
    console.log(x);  // 2
  }
  console.log(x);  // 2
}
Output

let

let allows you to declare variables that are limited in scope to the block, statement, or expression in which they are used. 
if you run the below the code it will throw an error

if (true) {
let name = 'Hi Shaik';
}
alert(name); //generates an error

In this above case, the name variable is accessible only in the scope of the if statement because it was declared as let.
Ex:
function letTest() {
  let x = 1;
  if (true) {
    let x = 2;  // different variable
    console.log(x);  // 2
  }
  console.log(x);  // 1
}
Output


const

const variables have the same scope as variables declared using let. The difference is that const variables are immutable - they are not allowed to be reassigned.

Ex:
const a = 'Hello Shaik';
a = 'Bye';
console.log(a);
Output

No comments:

Post a Comment