Articles

Es6 Variable Declaration

October 26, 2019

  1. Ways To Declare Variables In JavaScript

    There are three ways to declare variables in the javascript given below:-

  2. Var

  3. Let

  4. Const

  5. Difference Between Var,Let,Const.

Variable Declaration with let and const and var

//ES5
var x = 10;
x = 12;
console.log(x);//12
12;
//ES6
let x = 10;
x = 12;
console.log(x); //12
//ES6
const y = 14;
y = 12; //TypeError: Assignment to constant variable.
console.log(y);

Scope of Let,Const and Var

var a //declaration a = 2 // initialization let b //declaration b = 12 //initialization var c = 6 //declaration plus initialization in one step let d = 5 //declaration plus initialization in one step const a ; // SyntaxError: Missing initializer in const declaration a = 2; console.log(a); const a = 5 console.log(a) //5

1: when we start our variable with var, let is called declaration. e.g: var a; or let a; 2: when we start our variable and assigning value it is declaration and initialization with value 3: const cannot be declared only, you need to initialize it with declaration

Let and const have a block scope but var has function scope.

//ES5
function adult5(age) {
  if (age > 18) {
    var status = 'adult';
  }
  console.log(status); //adult
}
adult5(20);
/ ES6
function adult6(age) {
  if (age > 18) {
    let status = 'adult';
  }
  console.log(status); //ReferenceError: status is not defined
}
adult6(20);

1: var and let can change their value and const cannot change its value 2: var can be accessible anywhere in function but let and const can only be accessible inside the block where they are declared.