I am from C++ background and new to java script and having difficulty understand for loop scope. What is the scope of variable initialized inside for loop.
//Setup
var contacts = [
{
"firstName": "Akira",
"lastName": "Laine",
"number": "0543236543",
"likes": ["Pizza", "Coding", "Brownie Points"]
},
{
"firstName": "Harry",
"lastName": "Potter",
"number": "0994372684",
"likes": ["Hogwarts", "Magic", "Hagrid"]
},
{
"firstName": "Kristian",
"lastName": "Vos",
"number": "unknown",
"likes": ["Javascript", "Gaming", "Foxes"]
}
];
function lookUpProfile(firstName, prop){
for(var i=0;i<contacts.length;i++){
if(contacts[i].firstName==firstName){
if(contacts[i].hasOwnProperty(prop))
return contacts[i][prop];
else
return "No such property";
}
}
if (i === contacts.length)
return "No such contact";
}
// Change these values to test your function
lookUpProfile("Akira", "likes");
I am confused how if (i === contacts.length)
variable "i" is used outside for loop, variable "i" is initialize inside for loop and if statement is written out of scope of for loop. Value of document.write(i)
is equal to 4 when printed outside loop.Can somebody please explain this?