Why do many javascript libraries look like this:
(function () {
/* code goes here */
})();
It appears to define an unnamed function which is immediately called. Why go through this effort?
A function in JavaScript is similar to a procedure—a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output.
In JavaScript, a function allows you to define a block of code, give it a name and then execute it as many times as you want. A JavaScript function can be defined using function keyword.
require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object. require() statement not only allows to add built-in core NodeJS modules but also community-based and local modules.
There are 3 ways of writing a function in JavaScript: Function Declaration. Function Expression. Arrow Function.
This is standard way to do namespacing in JavaScript. If you just declare
var my_cool_variable = 5;
it will be global and might conflict with other libraries, that use the same variable.
However, if you do
(function() {
var my_cool_variable = 5;
})();
it is now local variable for anonymous function and is not visible outside of the scope of that function. You still can expose accessible API by not stating var
in front of variable, that way it will be global but now you have a choice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With