- Javascript Basics Tutorial
- Javascript - Home
- JavaScript - Overview
- JavaScript - Features
- JavaScript - Enabling
- JavaScript - Placement
- JavaScript - Syntax
- JavaScript - Hello World
- JavaScript - Console.log()
- JavaScript - Comments
- JavaScript - Variables
- JavaScript - let Statement
- JavaScript - Constants
- JavaScript - Data Types
- JavaScript - Type Conversions
- JavaScript - Strict Mode
- JavaScript - Reserved Keywords
- JavaScript Operators
- JavaScript - Operators
- JavaScript - Arithmetic Operators
- JavaScript - Comparison Operators
- JavaScript - Logical Operators
- JavaScript - Bitwise Operators
- JavaScript - Assignment Operators
- JavaScript - Conditional Operators
- JavaScript - typeof Operator
- JavaScript - Nullish Coalescing Operator
- JavaScript - Delete Operator
- JavaScript - Comma Operator
- JavaScript - Grouping Operator
- JavaScript - Yield Operator
- JavaScript - Spread Operator
- JavaScript - Exponentiation Operator
- JavaScript - Operator Precedence
- JavaScript Control Flow
- JavaScript - If...Else
- JavaScript - While Loop
- JavaScript - For Loop
- JavaScript - For...in
- Javascript - For...of
- JavaScript - Loop Control
- JavaScript - Break Statement
- JavaScript - Continue Statement
- JavaScript - Switch Case
- JavaScript - User Defined Iterators
- JavaScript Functions
- JavaScript - Functions
- JavaScript - Function Expressions
- JavaScript - Function Parameters
- JavaScript - Default Parameters
- JavaScript - Function() Constructor
- JavaScript - Function Hoisting
- JavaScript - Self-Invoking Functions
- JavaScript - Arrow Functions
- JavaScript - Function Invocation
- JavaScript - Function call()
- JavaScript - Function apply()
- JavaScript - Function bind()
- JavaScript - Closures
- JavaScript - Variable Scope
- JavaScript - Global Variables
- JavaScript - Smart Function Parameters
- JavaScript Objects
- JavaScript - Number
- JavaScript - Boolean
- JavaScript - Strings
- JavaScript - Arrays
- JavaScript - Date
- JavaScript - DataView
- JavaScript - Math
- JavaScript - RegExp
- JavaScript - Symbol
- JavaScript - Sets
- JavaScript - WeakSet
- JavaScript - Maps
- JavaScript - WeakMap
- JavaScript - Iterables
- JavaScript - Reflect
- JavaScript - TypedArray
- JavaScript - Template Literals
- JavaScript - Tagged Templates
- Object Oriented JavaScript
- JavaScript - Objects
- JavaScript - Classes
- JavaScript - Object Properties
- JavaScript - Object Methods
- JavaScript - Static Methods
- JavaScript - Display Objects
- JavaScript - Object Accessors
- JavaScript - Object Constructors
- JavaScript - Native Prototypes
- JavaScript - ES5 Object Methods
- JavaScript - Encapsulation
- JavaScript - Inheritance
- JavaScript - Abstraction
- JavaScript - Polymorphism
- JavaScript - Destructuring Assignment
- JavaScript - Object Destructuring
- JavaScript - Array Destructuring
- JavaScript - Nested Destructuring
- JavaScript - Optional Chaining
- JavaScript - Global Object
- JavaScript - Mixins
- JavaScript - Proxies
- JavaScript Versions
- JavaScript - History
- JavaScript - Versions
- JavaScript - ES5
- JavaScript - ES6
- ECMAScript 2016
- ECMAScript 2017
- ECMAScript 2018
- ECMAScript 2019
- ECMAScript 2020
- ECMAScript 2021
- ECMAScript 2022
- JavaScript Cookies
- JavaScript - Cookies
- JavaScript - Cookie Attributes
- JavaScript - Deleting Cookies
- JavaScript Browser BOM
- JavaScript - Browser Object Model
- JavaScript - Window Object
- JavaScript - Document Object
- JavaScript - Screen Object
- JavaScript - History Object
- JavaScript - Navigator Object
- JavaScript - Location Object
- JavaScript - Console Object
- JavaScript Web APIs
- JavaScript - Web API
- JavaScript - History API
- JavaScript - Storage API
- JavaScript - Forms API
- JavaScript - Worker API
- JavaScript - Fetch API
- JavaScript - Geolocation API
- JavaScript Events
- JavaScript - Events
- JavaScript - DOM Events
- JavaScript - addEventListener()
- JavaScript - Mouse Events
- JavaScript - Keyboard Events
- JavaScript - Form Events
- JavaScript - Window/Document Events
- JavaScript - Event Delegation
- JavaScript - Event Bubbling
- JavaScript - Event Capturing
- JavaScript - Custom Events
- JavaScript Error Handling
- JavaScript - Error Handling
- JavaScript - try...catch
- JavaScript - Debugging
- JavaScript - Custom Errors
- JavaScript - Extending Errors
- JavaScript Important Keywords
- JavaScript - this Keyword
- JavaScript - void Keyword
- JavaScript - new Keyword
- JavaScript - var Keyword
- JavaScript HTML DOM
- JavaScript - HTML DOM
- JavaScript - DOM Methods
- JavaScript - DOM Document
- JavaScript - DOM Elements
- JavaScript - DOM Forms
- JavaScript - Changing HTML
- JavaScript - Changing CSS
- JavaScript - DOM Animation
- JavaScript - DOM Navigation
- JavaScript - DOM Collections
- JavaScript - DOM Node Lists
- JavaScript Miscellaneous
- JavaScript - Ajax
- JavaScript - Async Iteration
- JavaScript - Atomics Objects
- JavaScript - Rest Parameter
- JavaScript - Page Redirect
- JavaScript - Dialog Boxes
- JavaScript - Page Printing
- JavaScript - Validations
- JavaScript - Animation
- JavaScript - Multimedia
- JavaScript - Image Map
- JavaScript - Browsers
- JavaScript - JSON
- JavaScript - Multiline Strings
- JavaScript - Date Formats
- JavaScript - Get Date Methods
- JavaScript - Set Date Methods
- JavaScript - Modules
- JavaScript - Dynamic Imports
- JavaScript - BigInt
- JavaScript - Blob
- JavaScript - Unicode
- JavaScript - Shallow Copy
- JavaScript - Call Stack
- JavaScript - Reference Type
- JavaScript - IndexedDB
- JavaScript - Clickjacking Attack
- JavaScript - Currying
- JavaScript - Graphics
- JavaScript - Canvas
- JavaScript - Debouncing
- JavaScript - Performance
- JavaScript - Style Guide
- JavaScript Useful Resources
- JavaScript - Questions And Answers
- JavaScript - Quick Guide
- JavaScript - Functions
- JavaScript - Resources
JavaScript - Self-Invoking Functions
Self-Invoking Functions
The self-invoking functions are JavaScript functions that execute immediately as they are defined. To define a self-invoking function, you can enclose an anonymous function within parentheses followed by another set of parentheses. These are also called self-executing anonymous functions.
The anonymous function inside the first pair of parentheses is basically a function defined with function expression. So a self-invoking function is also called immediately invoked function expression (IIFE).
Syntax
The syntax to define the self-invoking functions in JavaScript is as follows −
(function () { // function body })();
The function definition is enclosed inside the pair of parentheses. The second pair of parentheses at the end executes the function.
An alternative syntax is as follows −
(function () { // function body }());
The first syntax is more clear.
Example
In the example below, we print the message in the output using the self-executing function.
<html> <body> <p id = "output"> </p> <script> (function () { document.getElementById("output").innerHTML = "Self-invoked function is executed!"; }()); </script> </body> </html>
Output
Self-invoked function is executed!
Self-Invoking Functions with Parameters
You can create a self-invoking function with parameters and pass arguments to it. It is common practice to pass references to global objects such as window, etc.
(function (paras) { // function body })(args);
The paras are the list of parameters in the definition of the anonymous function and the args are arguments passed.
Example
In the below example, we created an anonymous function with a parameter name. We have passed an argument to it.
<html> <body> <div id = "demo"></div> <script> const output = document.getElementById("demo"); (function (name) { output.innerHTML = `Welcome to ${name}`; })("Tutorials Point !"); </script> </body> </html>
Output
Welcome to Tutorials Point !
Private Scope of Self-Invoking Functions
Whatever code is defined inside the self-executing function remains in the private scope and doesn't pollute the global scope. So, developers can make code clear and remove the errors like naming conflicts, etc. Also, the code of the self-invoking function remains hidden and can't be accessible by other parts of the code.
Example
In the example below, we have defined the variable 'a' outside or inside the function. The variable defined outside is a global variable, and the variable defined inside the function is a private variable, limited to the self-executing function's scope.
Also, we have printed the value of the variable from inside and outside of the function. Users can observe the variable's value in the output.
In this way, we can avoid the naming conflicts.
<html> <body> <div id = "output"> </div> <script> const output = document.getElementById("output"); let a = 10; (function () { output.innerHTML += "Entering to the function <br/>"; var a = 20; output.innerHTML += "The value of a is " + a + "<br>"; output.innerHTML += "Exiting to the function <br/>"; }()); output.innerHTML += "The value of the outside the function is " + a; </script> </body> </html>
Output
Entering to the function The value of a is 20 Exiting to the function The value of the outside the function is 10
Example
In some cases, it is required to access the variable of the self-executing function outside of the function. In this case, we can make that variable global using the 'window' object as shown below and access the variable in the global scope.
<html> <body> <div id = "output"> </div> <script> (function () { var string = "JavaScript"; window.string = string; })(); document.getElementById("output").innerHTML = "The value of the string variable is: " + string; </script> </body> </html>
Output
The value of the string variable is: JavaScript
Private scope of a self-invoking function can be accessed by using the call() or apply() methods.
Benefits of Using the Self-Invoking Functions
Avoiding the global scope − Developers can avoid the global scope for variables and functions using the self-invoking function, helping to avoid naming conflict and making code more readable.
Initialization − The self-executing functions can be used for the initialization of variables.
Code privacy − Programmers can avoid accessing the code of the self-executing function by other parts of the code.