It can be said that a variable declared with var is defined throughout the program as compared to let.
An example will clarify the difference even better
Example of var:
Input: console.log(x); var x=5; console.log(x); Output: undefined 5
Example of let:
Input: console.log(x); let x=5; console.log(x); Output: Error
In the following code, clicking start will call a function that changes the color of the two headings every 0.5sec. The color of first heading is stored in a var and the second one is declared by using let.
Both of them are then accessed outside the function block. Var will work but the variable declared using let will show an error because let is block scoped.
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : princeagrawal701