Saved Bookmarks
| 1. |
Differences between declaring variables using var, let and const. |
||||||||||||||||||||
|
Answer» Before the ES6 version of javascript, only the keyword var was used to declare variables. With the ES6 Version, keywords let and const were introduced to declare variables.
Let’s understand the differences with examples: var variable1 = 23;let variable2 = 89; function catchValues(){ console.log(variable1); console.log(variable2); // Both the variables can be accessed anywhere since they are declared in the global scope } window.variable1; // Returns the value 23 window.variable2; // Returns undefined
var vs let in functional scope function varVsLetFunction(){let awesomeCar1 = "Audi"; var awesomeCar2 = "Mercedes"; } console.log(awesomeCar1); // Throws an error console.log(awesomeCar2); // Throws an error Variables are declared in a functional/local scope using var and let keywords behave exactly the same, meaning, they cannot be accessed from outside of the scope. {var variable3 = [1, 2, 3, 4]; } console.log(variable3); // Outputs [1,2,3,4] { let variable4 = [6, 55, -1, 2]; } console.log(variable4); // Throws error for(let i = 0; i < 2; i++){ //Do something } console.log(i); // Throws error for(var j = 0; j < 2; i++){ // Do something } console.log(j) // Outputs 2
Const keyword
x = {address: "India"}; // Throws an error x.name = "Nikhil"; // No error is thrown const y = 23; y = 44; // Throws an error In the code above, although we can change the value of a property inside the variable declared with const keyword, we cannot completely reassign the variable itself. |
|||||||||||||||||||||