Alf Moh Alf Moh - 10 months ago 56
Javascript Question

Confusion about scope and hoisting in Javascript

<link rel="stylesheet" href="styles.css"/>
<ul id="people-list"></ul>
<script src="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;
alert("You clicked on "+ person);

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.

Answer Source

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.