Below is an expression where the anonymous function is evaluated and result is assigned to variable
x.
var x = function() {
console.log("Function ran");
}();
If we don't assign it to a variable, there will be a syntax error.
function() {
console.log("Function ran");
}();
You'd get a syntax error, because the JS parser thinks it is a statement. Below will work:
function f() {
console.log("Function ran");
};
f();
If you notice the above worked as the function has now a name and then we called the function.
But then how do we make the parser know that we want an anonymous function as an expression?
would see the 'function' keyword and assume you're starting a function statement of the form:
If an entire javascript is about execution of a function then the function need to be an anonymous function with parenthesis around it.
(
function() {
console.log("Function ran");
}
)();
Output:
Function ran
No comments:
Post a Comment