New course! Every coder should learn Generative AI!
Try a free lesson+ 7
What is the difference between 'var' and 'let' in javascript?
Both seemed having same functionality :/
5 Answers
+ 5
Let has more limited scope.
E.g. you declare a variable within a function with let keyword.
if you try to use that variable somewhere outside the function you'll get an error saying the variable hasn't been declared.
+ 10
This has a great explanation of the differences.
https://stackoverflow.com/questions/762011
+ 5
https://www.sololearn.com/Discuss/1256607/?ref=app
https://www.sololearn.com/Discuss/1248231/?ref=app
+ 2
var declares a global variable, let declares a variable within a scope e.g. in a function
function sololearn() {
let c="sololearn";
window.alert(c); //outputs sololearn
}
this will work fine but if I use it like:
function sololearn() {
let c="sololearn";
}
alert(c); //outputs undefined
because the variable isn't declared with a global scope.
- 3
let is a constant, while var is not