Day 63 JavaScript Safe Code IIFE

Immediately invoked function expression (IIFE). The act to safely encapsulate function so that it does not collide with any other functions in the code.

How to make an IIFE:

Normally to create a function you just type in function then the function name. The syntax parser within JavaScript automatically assumes there to be a function name after the word function. So invoking a function without a function name causes the code to be undefined.

You can override the parser by creating a normal function expression. In a normal function expression you create a variable equal to the function. By doing so the parser sets in memory the function during the creation phase.

However in IIFE you bypass this in a different way instead of creating a variable you add a parenthesis before the function so that the parser doesn’t see the word function first. Instead you write the whole function inside of the parenthesis and innovate it immediately after creation. Having the variable name inside of the function as well to keep the execution stack slim. IIFE holds the function, variable, and execution command all in one. This prevents crashing into any other part of the rest of the code. The code is inside of its own lexical environment.

This method of writing functions is emphasized due to large open source libraries taking this approach to writing their code. Libraries like jQuery etc use IIFEs. A new practice has been to look at open source projects code to see good coding mannerism.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Up ↑

%d bloggers like this: