I'm new to JavaScript, and am learning it from an online tutorial. The current expression is about the use of function expressions, and specifically - returning a function expression from inside a function.
Here's the code:
//array of all available rides, with respective wait times
var parkRides = [["Birch Bumpers", 40], ["Pines Plunge", 55], ["Cedar Coaster", 20], ["Ferris Wheel of Firs", 90]];
//array of fast pass rides, indicating next up ride
var fastPassQueue = ["Cedar Coaster", "Pines Plunge", "Birch Bumpers", "Pines Plunge"];
//function to build fast pass queue using array
function buildTicket(allRides, passRides, pick) {
//if user has picked the first ride in fast pass queue, alert so...
if(pick == passRides[0]) {
//remove first item from queue using shift and store it in a var
var pass = passRides.shift();
//return function expression here
return function () {
alert("QuicK!! You've got a fast pass to " + pass + "!");
}; //return ends with a ;
}
else {
for (var i = 0; i < allRides.length; i++) {
if(pick == allRides[i][0]) {
//return a function expression here
return function () {
alert("A ticket is printing for " + allRides[i][0] +"!\n"+ " Your wait time is about " + allRides[i][1] + " minutes.");
};
}
}
}
}
//use function buildticket
var wantsRide = "Pines Plunge";
var ticket = buildTicket(parkRides, fastPassQueue, wantsRide);
//execute function expression by calling ticket()
ticket();
I'm using MS Visual Studio Code, and at the end of the code, I get one error and one warning, even though the code successfully works, and I get the desired result depending on the wantsRide
variable. However, I failed to understand the reason for the error and warning.
At the bottom of the screen(screenshot below), I get 1 cross and 1 exclamation icon, I assume that means 1 error and 1 warning.
But when I click on it, I get a highlighted area on the top of the bar that says ! Function inside loop
and these lines are highlighted:
return function () {
alert("A ticket is printing for " + allRides[i][0] +"!\n"+ " Your wait time is about " + allRides[i][3] + " minutes.");
};
What seems to be the problem here? I know it's a function expression inside a for
loop, but why is the warning generated? Is it because it the if(pick==allRides[i][0])
statement might never be true, so the function expression would never get executed?