Alf Moh Alf Moh - 1 month ago 9
Javascript Question

Confusion about scope and hoisting in Javascript

<!DOCTYPE>
<html>
<head>
<link rel="stylesheet" href="styles.css"/>
<body>
<ul id="people-list"></ul>
<script src="app.js"/>
</body>
</head>
</html>

***app.js***

var people = ["alf","kay","jay","may"];
var list = document.getElementById("people-list");
for(var i =0; i< people.length; i++){
var person = people[i];
var element = document.createElement("li");
(function (){
var person = person;
element.innerText = person;
element.addEventListener("click",function(){
alert("You clicked on "+ person);
});
}());
list.appendChild(element);
}


Why is the "person" variable created in the Global Scope not being referenced in the IIFE and therefore produces a list of undefineds but then a change in variable name from (example. var person to var person2 and subsequent change in the alert) in IIFE makes the code work correctly.

JJJ JJJ
Answer

Due to hoisting var person = person is exactly equivalent to

var person;
person = person;

You can't refer to the person variable in the outer scope. It's completely overshadowed by the local variable, so you're assigning the undefined local variable to itself.

Comments