Javascript: Normal, Anonymous, and IIFE Functions.

First thing.

FUNCTION VALUES MUST BE EXPLICITLY RETURNED!!!How to explicitly return a value in a function.


function realExample(){ return 21+21}=> 42There you go.

The answer to life, universe and everything.

Let’s add a bit more complexity to this function by adding arguments.

We do this by putting them in the parenthesis.


function realExample(num1, num2){ return num1+num2}Here is where a functions’…erm…functionality really becomes useful and dynamic.


realExample(21,21)=> 42The meaning of everything.

Now whenever you want to add two things together, you can use the function.

realExample("forty","-two")=> "forty-two"Universe.



Anonymous FunctionsAn anonymous function is a function that is… ummm… anonymous.

It doesn’t have a name.

However it can be stored in a variable and run essentially the same way.

Example:let universe = function (num1, num2){return num1+num2}Notice the lack of function name, we've saved it to a variable.

This is what makes it anonymous.

Calling Anonymous FunctionsPretty much the same as calling a regular function, but you call the variable name since there is no function name.

Then you can save it to a different variable if you’d like.


let universe = function (num1, num2){ return num1+num2}universe(21,21)=> 42let everything = universe(21,21)everything=> 42let nothing = universe(0,0)nothing=> 0IIFE (Immediately Invoked Function Expression)This is a juicy one.

It’s used to save space and make your code look cleaner.

Coding is about efficiency and clarity.

When you have a bunch of functions that you want called immediately on page load, use IIFE to save space and make your code more readable.

Let’s look at the normal way again.

function realExample(){ return 21+21}universe()=> 42The IIFE equivalent.

(function(){ return 21+21})()=> 42Value is returned immediately.

Here is an overview of whats happening.

You write an unnamed function in parenthesis, then add a set of parenthesis after to call it.

start with empty parenthesis1.

(); write unnamed function inside those parenthesis2.

(function(){ return 21+21});call function by adding a set of parenthesis at the end.


(function(){ return 21+21})(); => 42Now you can pass in arguments to add complexity and dynamism.

(function(num1,num2){ return num1+num2})(21,21); => 42Like I said, maybe you want a function to fire on page load, use the IIFE.

Try this out.

Copy and past the below into your console(left click anywhere on page, click console tab, paste code in and hit enter.

(function() { alert('You Wrote an IIFE!!!') })();Hopefully you get this alert.

Also you can see I am writing this article while I thought of this analogy, what improvisation!There are a couple syntactical ways to write an IIFE, I like to simplify first, and then branch out later.

Watch out for those syntax errors.

It’s parenthesis I swear.

Enjoy!Rources:W3schoolsMDN Functions.. More details

Leave a Reply