MJSQ 101: IIFE, anonymous functions, native vs host objects
Dan-Vy Le
Posted on February 5, 2020
More JavaScript Questions 101(MJSQ 101):
Continuing from my original blog post, more javascript 101 questions!:
Explain why the following doesn't work as an IIFE: function foo(){ }();
. What needs to be changed to properly make it an IIFE?
First you'll need to understand what an IIFE is. An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined.
(function () {
var whoWonSuperBowl = "Kansas City Chiefs";
return whoWonSuperBowl;
})();
//output: "Kansas City Chiefs"
function foo() {} ();
is reading the two as separate: function foo(){}
as a function declaration and then ()
as a function call. Since they are not grouped, the function throws an error: Uncaught SyntaxError: Unexpected token
.
To fix this, we can call on the grouping operator ( )
to group the function declaration and immediately invoke the function (function foo(){ })()
or group the entire function together with (function foo(){ }())
to create function expressions that can be immediately invoked.
What's a typical use case for anonymous functions?
IIFE which was mentioned above:
(function() {
//expression
})();
As a callback where naming the function isn't necessary and it won't need to be used anywhere else(Yangshun's example):
setTimeout(function() {
console.log('Hello world!');
}, 1000);
What's the difference between host objects and native objects?
Native objects are objects that are unique to the JavaScript language. Some examples include: String, Number, Array, Image, Date, Math, etc.
Host objects are objects that are supplied to JavaScript by the browser environment. Examples of these are window, document, forms, etc.
That's all for today, please leave any comments/questions/corrections in the comments. Thanks!
Sources:
Huge huge thanks to github user: yangshun for aggregating the most popular JS, CSS and HTML questions and giving us his answers to it. My weekly blog posts are to go over several questions at a time to reinforce my knowledge of fundamental javascript as I grow my expertise in it. Many of my blog will be paraphrasing if not direct quote from his github. Find his tech interview handbook here and please support him!
And an additional thank you to Flatiron alum: Marissa O. who is a badass developer at Forbes magazine for directing me to his blog!
Other sources:
Posted on February 5, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.