Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Why do we use a plus sign in front of function name in JavaScript?
The +function() {} notation is primarily used to force the parser to treat whatever follows the + as an expression. This is commonly used for Immediately Invoked Function Expressions (IIFEs).
The Problem Without +
Without the plus sign, JavaScript interprets a function declaration, which cannot be immediately invoked:
// This causes a syntax error
function() { console.log("Demo!"); }();
Using + to Create an IIFE
The + operator converts the function declaration into an expression, allowing immediate invocation:
IIFE with Plus Sign
Alternative Operators
You can use other unary operators like !, -, or ~ to achieve the same result:
IIFE Alternatives
Using Parentheses (Most Common)
Parentheses are the most popular and readable way to create IIFEs:
IIFE with Parentheses
Comparison
| Method | Readability | Common Usage |
|---|---|---|
+function() {}() |
Good | Uncommon |
!function() {}() |
Good | Occasional |
(function() {})() |
Excellent | Very Common |
Conclusion
The + sign forces function declarations to become expressions for immediate invocation. However, parentheses are preferred for better readability and convention in modern JavaScript.
