Hello everyone in the group,
I wrote a JavaScript snippet to retrieve the elements that I click on. However, when I declare the variable using "var," it only shows the last clicked element as the result. But when I use "let" for declaration, it gives me the desired outcome (retrieving the correct element that I click on).
Below is the image when I declare using "var":
And here is the image when I use "let":
I hope someone can help me clarify why, when declaring with "var," it only prints the last element. Thank you, everyone, for your assistance.
I want to display the element that I click on.
3
Answers
Click on h2 elements to get clicked elements
click on any elements to get element printed on console.
What’s the actual problem in this case? Since you’re saying:
You’ve solved your own problem. Or is
let
something you don’t want to use? In that case please explain why. Otherwise, just uselet
.Maybe it’s also a good idea to look at this post which explains the differences between
var
andlet
.There is significant difference between the usage of
var
andlet
keywords in javascript.let
will only be available inside the block of thefunction or method in which it is being declared. which is known as
blocked-scope
.let
javascript’sHoisting
will not beallowed.
var
will be available even outside of the method orfunction that they are created on. Which is known as
global-scope
javascript.
var
javascript will allow hoisting ontoit
In your case, if you are using
let
and it solves the problem then most probably it can be a scope-related issue.