Avatar of milani_lucie
milani_lucie
Flag for United States of America asked on

Closure in JavaScript

Hi,

I have written the code in JavaScript two ways (WAY-1.html, WAY-2.html). Find the attachments. The second way (WAY-2.html) works fine as expected. Can you please do let me know why ? BTW: What is this "Closure" thing ? Also please explain a little bit !

Thanks
WAY-1.html
WAY-2.html
JavaScript

Avatar of undefined
Last Comment
nap0leon

8/22/2022 - Mon
nap0leon

In "Way1", because your function looped through everything when the page loaded, the value of "i" is 5, so you alert('5') every time you click.

In "Way2", you created a function call on each item.  This function call passes the value that "i" was at the time of the function creation.  In this way, your page is able to alert('1'), alert('2'), etc.
milani_lucie

ASKER
I am still NOT clear ... Can you please explain me in simple terms ?

WAY - 1

elements(i).onclick = function() { alert(i); };

means

if i = 0 then alert(0)
if i = 1 then alert(1)
if i = 2 then alert(2)
if i = 3 then alert(3)
if i = 4 then alert(4)

Am i correct ?

Thanks
HonorGod

All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
milani_lucie

ASKER
Sorry ... I cannot go through the entire story with deep URLs. Please provide me point-to-point explanation so that i can understand it better !! Even i have provided you the code also.

Thanks
ASKER CERTIFIED SOLUTION
nap0leon

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.