+ 1

What is the difference between var and let in js

So I know you can use var.X and let X= to create a variable named X but what is the difference? Pls help😄

13th Nov 2024, 4:39 PM
Keystone745
8 Answers
+ 5
Try searching on search bar before posting a question. https://www.sololearn.com/Discuss/3307764/?ref=app
14th Nov 2024, 1:23 AM
Gulshan Mahawar
Gulshan Mahawar - avatar
+ 4
Quoting from Javascript Intermediate: "Unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope, let allows you to declare variables that are limited in scope to the block, statement, or expression in which they are used."
13th Nov 2024, 4:43 PM
Lisa
Lisa - avatar
+ 3
do you mean var X = document.getElementById("x") ? there must be no "." between var and X.
13th Nov 2024, 4:58 PM
Lisa
Lisa - avatar
+ 1
Thank you
13th Nov 2024, 4:55 PM
Keystone745
0
Can I use var.X. With document.getElementById
13th Nov 2024, 4:56 PM
Keystone745
0
Oh
13th Nov 2024, 5:02 PM
Keystone745
0
That is what i mean but i just thought you still had to use dot notation
13th Nov 2024, 5:02 PM
Keystone745
0
Redeclare var x = 2; var x = 3; /* The variable x is first declared ati store 2, the updated to store 3.. this syntax will be correct. */ let x = 4; let x = 5; /* This will give a syntax error you cannot redeclare an already declared variable you just have to update it like x= 5 */ Scope for (var i = 0; i < 5; i++) { console.log(i) /* this will return results 1 2 3 4 */ } console.log(i) //this will return 5 for (var j = 0; j < 5; j++) { console.log(j) /* this will return results 1 2 3 4 */ } console.log(j) /* this will give a reference error stating j is not defined */ From this we can see that let is block specific which means that a variable declared with let is only accessible via the block in which it was originally declared in, unlike var which was accessed outside the loop which tells us it's not block specific but more general
15th Nov 2024, 9:02 AM
Caleb Lumene
Caleb Lumene - avatar