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:

<html>
<head>
    <title>IIFE with Plus Sign</title>
</head>
<body>
    <script>
        +function() { 
            alert("Demo with + sign!"); 
        }();
    </script>
</body>
</html>

Alternative Operators

You can use other unary operators like !, -, or ~ to achieve the same result:

<html>
<head>
    <title>IIFE Alternatives</title>
</head>
<body>
    <script>
        !function() { alert("Using ! operator"); }();
        -function() { alert("Using - operator"); }();
        ~function() { alert("Using ~ operator"); }();
    </script>
</body>
</html>

Using Parentheses (Most Common)

Parentheses are the most popular and readable way to create IIFEs:

<html>
<head>
    <title>IIFE with Parentheses</title>
</head>
<body>
    <script>
        // Method 1: Parentheses around function
        (function() { alert("Method 1"); })();
        
        // Method 2: Parentheses around entire expression
        (function() { alert("Method 2"); }());
    </script>
</body>
</html>

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.

Updated on: 2026-03-15T21:42:06+05:30

388 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements