Skip to content
Related Articles

Related Articles

What is the syntax for leading bang! in JavaScript function ?

View Discussion
Improve Article
Save Article
  • Last Updated : 03 Mar, 2022
View Discussion
Improve Article
Save Article

Before we get to know the syntax for the leading bang! in a JavaScript function, let’s see what functions in JavaScript are actually are.

JavaScript functions are a set of statements(procedures) that perform some tasks or calculate some value. A function may take some input and return the result to the user.

The main idea to use functions is to avoid doing the same work again and again for different inputs and writing the same code again and again. Instead, we can write a function of the task and call the function whenever required. The use of functions improves the readability of the program. JavaScript provides functionality to users to create their own user-defined functions.

Syntax:

function functionName(parameters) {
  // body of the function
}

Example: In this example, we have created a function sayHi, this function receives a single parameter and prints a message on the console.

Javascript




function sayHi(name) {
    console.log("Hey Geeks, Welcome to " + name);
}
let name = "GeeksforGeeks";
sayHi(name);


Output:

Hey Geeks, Welcome to GeeksforGeeks

The leading bang! the syntax is used to execute an anonymous function. It is alternate to the more common syntax for the self-invoking anonymous functions.

Syntax: The syntax for the leading bang! in JavaScript function 

!function () {
    // code
}();

The ideal way can be to achieve this would be as

function() {
    // code
} ();

The above statements mean to declare the anonymous function and execute it. It actually will not work because of the specifics of JavaScript grammar. The shortest way to achieve the above functionality is using the leading bang! syntax.

Example: This is the most common syntax for self-invoking anonymous functions.

Javascript




(function () {
    console.log("Welcome to GeeksforGeeks");
})();


Output:

Welcome to GeeksforGeeks

Below is the syntax for the leading bang! in JavaScript functions:

Javascript




! function () {
    console.log("Welcome to GeeksforGeeks");
}();


Output:

Welcome to GeeksforGeeks

Example 2: The most common syntax for self-invoking anonymous functions.

Javascript




let num1 = 10;
let num2 = 10;
  
(function (a, b) {
    console.log(a * b);
})(num1, num2);


Output:

100

Below is the syntax for the leading bang! in JavaScript functions for the same work.

Javascript




let num1 = 10;
let num2 = 10;
  
! function (a, b) {
    console.log(a * b);
}(num1, num2);


Output:

100

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!