Reputation: 3415
in the following javascript code I see there's a use of the command function, but it didn't specify the name of the function. What's this all about?
var getReview = function(movie) {
switch (movie) {
case "Matrix":
return "good trip out";
break;
case "Princess Bride":
return "awesome date night movie";
break;
case "Welcome to America":
return "Amjad's favorite";
break;
case "Remember the Titans":
return "love the sports";
break;
case "Why do I look like I'm 12?":
return "The Ryan and Zach story";
break;
case "Fighting Kangaroos in the wild":
return "Token Australian movie for Leng";
break;
default:
return "I don't know!";
}
};
Upvotes: 0
Views: 112
Reputation: 42450
It's an anonymous function.
Quoting from the link above:
Anonymous functions are declared using the function operator. You can use the function operator to create a new function wherever it’s valid to put an expression. For example you could declare a new function as a parameter to a function call or to assign a property of another object.
Here’s an example where a function is declared in the regular way using the function statement:
function eatCake() {
alert("So delicious and moist");
}
eatCake();
Here’s an example where the same function is declared dynamically using the function operator:
var eatCakeAnon = function() {
alert("So delicious and moist");
};
eatCakeAnon();
Upvotes: 2
Reputation: 225164
It's a function literal. It's exactly1 like a function, but doesn't have a name; it's just an object, like everything else in JavaScript, with the special part being that you can call it. Here, it's immediately assigned to getReview
, so you can call getReview()
to call the function.
1 Actually, its definition won't be hoisted, but you don't need to worry about that.
Upvotes: 2