We have 3 different ways to declare variables in java script
-
var - Variables declared with var keyword are function scoped. What do I mean by that ? let's take an example -
function sayHello(){ for(var i=0;i<4;i++){ console.log(i); } // As var is function scoped, i is available outside for loop. console.log(i); // This prints 4. } sayHello();
0 1 2 3 4
-
let - This is part of ES6 and addresses the problem related to var keyword. Variables declared with let keyword are block scoped.
Let's consider the previous code with let
function sayHello(){ for(let i=0;i<4;i++){ console.log(i); } // let is block scoped hence i is only visible inside for block. console.log(i); // This line will throw an error. } sayHello();
0 1 2 3 Uncaught ReferenceError: i is not defined at sayHello (:6:15) at :8:1
-
const - const keyword is used to define constants in java scripts and are block scoped. e.g.
function sayHello(){ const i = 1; console.log(i);// This prints 1 i = 2; // i is declared as constant hence this line will throw an error. } sayHello();
1 Uncaught TypeError: Assignment to constant variable. at sayHello (:4:4) at :6:1
Conclusion: With var keyword we may get unexpected output, so if the value of a variable is not expected to change then const keyword should be preferred else use let keyword to define variables.
Cheers!
Top comments (0)