JavaScript in the browser is the lacks namespacing. Every piece of code runs in the global scope; therefore, internal application code or third-party dependencies can pollute the scope while exposing their own pieces of functionality. Polluting global namespace causes name collision. This name collision is very common in large projects and can be extremely harmful.
Imagine, for instance, that a third-party library instantiates a global variable called utils. If any other library, or the application code itself, accidentally overrides or alters utils, the code that relies on it will likely crash in some unpredictable way. Unpredictable side effects can also happen if other libraries or the application code accidentally invoke a function of another library meant for internal use only.
(function () { // create state variables // make some operation // then return those const export = { export1: () => {}, export2: () => {} } return exported })()
it is used to create a private scope, exporting only the parts that are meant to be public.
Parentheses around function expressions
Why do we even need those? The reason is purely syntactical. The JavaScript parser has to be able to easily differentiate between function declarations and function expressions. If we leave out the parentheses around the function expression, and put our immediate call as a separate statement function(){}(3), the JavaScript parser will start processing it, and will conclude, because it’s a separate statement starting with the keyword function, that it’s dealing with a function declaration. Because every function declaration has to have a name (and here we didn’t specify one), an error will be thrown. To avoid this, we place the function expression within parentheses, signaling to the JavaScript parser that it’s dealing with an expression, and not a statement.
You might also see this in some projects:
+function(){}(); -function(){}(); !function(){}(); ~function(){}();
This time, instead of using parentheses around the function expressions to differentiate them from function declarations, we can use unary operators: + , - , ! , and ~. We do this to signal to the JavaScript engine that it’s dealing with expressions and not statements.