What are the Var,Let and Const keywords in JavaScript ?

ยท

2 min read

--> Var, Let and Const are keywords used in javascript to declare variables.

Why are there three types of declarative keywords in javascript?

--> In older versions of JavaScript we had only the Var keyword to declare variables but it has some drawbacks which were fixed in ECMAScript 6 on 17 June 2015.

--> In ECMAScript 6 two new keywords were introduced which are Let and Const. These keywords helped a lot of programmers to write better and more understandable codes in JavaScript.

Problems with the Var keyword.

1. Variables that are declared with the var keyword are function scoped. 2. If we declare a variable using the var keyword then we can declare the same variable using the same name again.

var myValue = 5;
var myValue = 10;
console.log(myValue); // output:10

3. Var keyword allows variable hoisting. Hoisting:- Hoisting in JavaScript allows variables and functions to be declared anywhere in the code.

x  = 5;
var x;
console.log(x); // output: 5

Advantages of Let and Const keywords.

1. Let & Const keywords both support block scoping.

let x  = 5;
{
let x = 10;
}
console.log(x); //output : 5
const x  = 5;
{
const x = 10;
}
console.log(x); //output : 5

2. The values which are declared using the Let keyword can only be updated and the values which are declared using the Const keyword can not be updated.

//Let keyword
let myValue = 5;
console.log(myValue); // output: 5
myValue = 10;
console.log(myValue); // output: 10
 const myValue = 5;
 console.log(myValue); // output: 5
 myValue = 10;  // TypeError: Assignment to constant variable.

3. Both the Let and Const keywords do not support Hoisting.

x = 5;
let x; //ReferenceError: Cannot access 'x' before initialization
x = 5;
const x; //SyntaxError: Missing initializer in const declaration

Did you find this article valuable?

Support Upendra Sahni by becoming a sponsor. Any amount is appreciated!

ย