Advertisement
728x90
You can list out the differences in a tabular format
| var | let |
| -------------------------------------------------------------- | --------------------------------------------- |
| It has been available from the beginning of JavaScript | Introduced as part of ES6 |
| It has function scope | It has block scope |
| Variable declaration will be hoisted, initialized as undefined | Hoisted but not initialized |
| It is possible to re-declare the variable in the same scope | It is not possible to re-declare the variable |
Let's take an example to see the difference,
javascript
1function userDetails(username) {
2
3if (username) {
4 console.log(salary); // undefined due to hoisting
5 console.log(age); // ReferenceError: Cannot access 'age' before initialization
6 let age = 30;
7 var salary = 10000;
8}
9
10console.log(salary); //10000 (accessible due to function scope)
11
12console.log(age); //error: age is not defined(due to block scope)
13}
14
15userDetails("John");Advertisement
Responsive Ad
🎯 Practice NowRelated Challenge
JavaScript Coding Exercise 20
Test your knowledge with this interactive coding challenge.
Start CodingAdvertisement
728x90
19of476