Search code examples
javascriptjavaangulariife

Is IIFE the same as initialize in Java development?


In java I use initialize to run whatever I need on the page immediately. In javascript, more specifically Angular I have

(function() {}());

This essentially does the same thing correct? Or are there differences?


Solution

  • An Immediately Invoked Function Expression (IIFE) can be used to initialize a page upon load, but it can also be used anywhere you have an anonymous function that needs to be called. Since the function is anonymous, it has no name and therefore can't be called by another caller. But, it can be invoked if it is written as an expression, immediately after it is written.

    Anonymous functions exist as a way to create "black boxes" of scope so that even the function name can not conflict with another identifier in the same scope or situations where the function won't need to be stored, so no name is needed.

    This situation comes up all over JavaScript and makes this pattern applicable in many other situations beyond page initialization.