Javascript function with an “!”
Have you ever encountered this line of code in Javascript and wonder what this means?
! function () { //Some code}();
It’s actually another way of writing a self-invoking function or self-executing function.
Self-invoking functions are functions that automatically call itself without the need of invoking it.
You can create a self-invoking function by enclosing your function in a parenthesis and add the () after your function.
(function () { //Some code})();
Or as explain above use ! in exchange of ().
If you are new to functions or you just want to see how this self-invoking functions evolved in it’s syntax from a basic function, continue reading on….
FUNCTION is a block of code that does a particular task or action.
A function can be declared in the following way:
- Anonymous Function Expression:
function () {
//Some code
};
2. Named Function Expression:
function name() {
//Some code
};
A function is used in the following way:
To use the anonymous functions, most of the time we try to pass it first into a variable:
var name = function () {
//Some code
};// To call/use it, type the name of the variable and add the () on the end.name();
To use the named functions:
function name() {
//Some code
};//To call/use it, just type the function name in with the ();name();
Now if you want to trigger the function right away without calling it, we use the self-invoking function (self-executing function) as discussed above. But i’ll discuss it again so you won’t need to go up….
Self-invoking or self-executing functions:
// You need to wrap the function into a parenthesis first, then add the () after the close parenthesis to call it right away.(function () { //Some code})();
Or instead of using the parethesis, we can use the “!”
// ! in exchange of the ()! function () {//Some code}();
NOTE: There are also functions with parameters inside it. These are just examples of functions without parameters to easily explain what is a self-invoking function and its syntax.
If this lesson has helped you in anyway, you can give it a ❤ or share it out. Thanks! :)