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 = "neveropen" ; sayHi(name); |
Output:
Hey Geeks, Welcome to neveropen
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 neveropen" ); })(); |
Output:
Welcome to neveropen
Below is the syntax for the leading bang! in JavaScript functions:
Javascript
! function () { console.log( "Welcome to neveropen" ); }(); |
Output:
Welcome to neveropen
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