0

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":enter image description here And here is the image when I use "let":enter image description here

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.

  • Please edit your question to remove the image and post the code instead. [Do not post code/errors/text in images](https://stackoverflow.com/help/how-to-ask). – Andy Ray Jul 05 '23 at 01:23
  • ```var``` is **outdated** but not **obsolete**, so you can still use it. But some of the browser today is sensetive when using an outdated declaration. So I suggest when you declaring a variable, just use ```let``` or ```const```. This is only my POV. – Newbee Jul 05 '23 at 01:41
  • 1
    `let` is scoped to the for loop body, `var` is scoped to the outer function. This is a duplicate question ['let' vs 'var' in javascript for loops, does it mean that all the for loops using the 'var i =0' should actually be 'let i =0' instead?](https://stackoverflow.com/questions/32313961/let-vs-var-in-javascript-for-loops-does-it-mean-that-all-the-for-loops-usin) – Andy Ray Jul 05 '23 at 02:39

0 Answers0