
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Difference Between var and let in JavaScript
To declare a variable in javascript we can use var, let or const keyword. Earlier var was only way to declare variable in javascript.In ES6, let and const keywords were introduced as a better way to declare variables. Now it is advised to use let instead of var to declare a variable.
In this article we will be understanding the differences between var and let in Javascript. We will be differentiating between let and var based on the features mentioned in the table:
Features | let | var |
---|---|---|
Scope | The let keyword is block scoped. | The let keyword is function scoped. |
Redeclaration | We can not redeclare variable if the variable is already declaraed earlier in the scope. | Variable can be redeclared again in same scope. |
Hoisting | Using let keyword variable are hoisted but due to Temporal Dead Zone(TDZ), it returns a RefrenceError. | Yes, var keyword allows hosting. |
Temporal Dead Zone (TDZ) | TDZ exists untill variable is declared. | TDZ doesn't exist. It returns undefined if used before declaration. |
Global Object Property | In global scope, let do not become properties of the global object. | In global scope, var becomes properties of the global object. |
Example 1
In this example, we have declared variable using let and var inside if statement which is inside a function. But the output is displayed only for var keyword because it is function scoped and let is block scoped.
<!DOCTYPE html> <html lang="en"> <head> <title> Scope in let and var </title> </head> <body> <div id="varkey"></div> <div id="letkey"></div> <script> function fun() { if (true) { var x = 50; let y = 20; } document.getElementById("varkey") .innerHTML = "var x = " + x; document.getElementById("letkey") .innerHTML = "let y = " + y; } fun(); </script> </body> </html>
Example 2
In this example, we are calling variable using var keyword before declaration which shows undefined in output, where as let keyword throws RefrenceError.
<!DOCTYPE html> <html lang="en"> <head> <title>Document</title> </head> <body> <div id="varkey"></div> <script> document.getElementById("varkey") .innerHTML = "var x = " + x; var x= 10; </script> </body> </html>
Conclusion
In this article, we discussed the between between let and var keyword on basis of various features such as scope, redeclaration, hoisting, TDZ and global object property with examples.