Reputation:
Why is the alert not working if I erase namePosition? Is Javascript read line by line(top to bottom) when executed? If yes then the alert should work because it is executed/read first before the return.
function positionIdentifier(name, nameArray) {
var namePosition;
for (i = 0; i < nameArray.length; i++) {
if (nameArray[i] == name) {
namePosition = function() {
alert("Your name is in position number " + (i + 1));
}
return namePosition;
}
}
}
name1Array = ["look", "sky", "walk", "kier"];
positionIdentifier("walk", name1Array)();
Upvotes: 0
Views: 67
Reputation: 65808
Your function runs as is, However, there is no need to declare/name the function that is going to be returned. Just return the function. This simplifies the code quite a bit. Also, you didn't declare your loop variable or your array variable with var
, which would cause them to become global. Remember to declare all variables.
function positionIdentifier(name,nameArray){
for(var i = 0; i < nameArray.length; i++){
if(nameArray[i] == name){
return function(){
alert("Your name is in position number "+(i+1));
}
}
}
}
var name1Array = ["look","sky","walk","kier"];
positionIdentifier("walk", name1Array)();
Upvotes: 2