syntax for the module pattern in Javascript [duplicate] - javascript

This question already has answers here:
Location of parenthesis for auto-executing anonymous JavaScript functions?
(4 answers)
Closed 6 years ago.
I am learning module pattern in Javascript, and have come across these two ways to create a module:
var Module = (function () {
// code
})();
var Module = (function () {
// code
}());
is there a significant difference in these two approaches? if not, which is considered the better practice? Thanks.

Both are the same. The outer round braces are forcing the inside code to be evaluated as an expression. This means that in both cases the function code is treated as function-expression as well. And then this function is immediately executed due to () braces.
So, it should be exactly the same from the point of view of JS interpreter todo list: 1) get function expression, 2) execute it right away.
It only differs from aesthetic point of view - which way it looks more natural for you.

Related

What is (function e(t,n,r){ ...}) in Javascript? [duplicate]

This question already has answers here:
What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?
(10 answers)
Closed 6 years ago.
I am studying the List.js Framework.
This is a starting code. If I remove it(even remove the surrounding "()" of function e), Code is not working.
What is this? I think it is already defined in Javascript method.
(function e(t,n,r){
function s(o,u){
if(!n[o]){
if(!t[o]){
var a=typeof require=="function"&&require;
if(!u&&a) return a(o,!0);
if(i)return i(o,!0);
var f=new Error("Cannot find module '"+o+"'");
throw f.code="MODULE_NOT_FOUND",f
}
var l=n[o]={exports:{}};
t[o][0].call(l.exports,function(e){
var n=t[o][1][e];
return s(n?n:e)
},l,l.exports,e,t,n,r)
}
return n[o].exports
}
var i=typeof require=="function"&&require;
for(var o=0;o<r.length;o++)
s(r[o]);
return s
}
)
It is a minified version of javascript (which does not make any actual difference, other than file size, and readability) so really, it is actually very much normal javascript code. However, written without the non compulsory syntax, unneeded whitespace, shorter variable names, all in efforts to reduce file transfer time.

Self-invoking JavaScript (brackets) [duplicate]

This question already has answers here:
Location of parenthesis for auto-executing anonymous JavaScript functions?
(4 answers)
Closed 6 years ago.
There is a piece of code :
(function aaa(){alert("555")})()
and this :
(function aaa(){alert("555")}())
What is the difference?
If you put the first one together twice, it only runs the first one before producing a TypeError:
(function aaa(){alert("555")})()(function aaa(){alert("555")})()
If you put the second one together twice, it runs both of them before producing a TypeError:
(function aaa(){alert("555")}())(function aaa(){alert("555")}())
In short, they're two different style choices for scoping code to avoid cluttering the global namespace, but the second one in my experience tends to be favored more since it's less prone to erroring when multiple scopes are concatenated together. It's best to always begin the scope with a semicolon to ensure that it executes when concatenated like so:
;(function aaa(){alert("555")}());(function aaa(){alert("555")}())

JavaScript function evaluating itself and calling itself at the same time [duplicate]

This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 7 years ago.
I am learning about JavaScript functions on MDN
I came across an example that looks similar to this:
var saySomething = ( function(){console.log("hello")} )();
I have also seen this in the jQuery source.
I have not found any explanation of this style of function calling/definition on the MDN function reference.
I know from running the code that it calls itself immediately upon interpretation by the JavaScript engine.
Is this the Grouping Operator in action? Where it says:
First evaluate the body of this function and return it
Since the parentheses () immediately follow it it gets called ?
Google "Immediately Invoked Function Expression" or "IIFE".
The general syntax looks like this:
(function(){
// do something here
})():
Sometimes you'll see arguments passed in as well. It's basically used to wrap your code so none of your variables leak out into the global namespace.

Self-executing anonymous function conventions [duplicate]

This question already has answers here:
Location of parenthesis for auto-executing anonymous JavaScript functions?
(4 answers)
Closed 8 years ago.
Is there any difference between the following? Do they all work in the same way?
I've seen certain use-cases for .call() but I've never seen an explanation as to why the function call brackets are either inside or after the anonymous function declaration.
(function() {
}());
^^
(function() {
})();
^^
(function() {
}).call();
The first two are the same, and differ by style only*; the last one is different in that it gives you the ability to control what the value of this will be inside the IIFE. For example
(function(){
this.a = 12;
}).call(foo);
will add the property a to the object foo.
*Of course Douglas Crockford has a preference
The location of the () inside or outside the main () doesn't matter in the slightest. (Much) more discussion in this other question, but that question doesn't address the call option you raised.
call requires at least one argument according to the specification, so to be largely the same as your first two options, you'd want:
(function() {
}).call(undefined);
...to be sure some implementation doesn't get uppity with you for not supplying the argument.
I prefer 2nd way. JSLint uses the first way. You should always use .call() with an argument, so the third variant is wrong.
There is no difference between 1 and 2 though.

javascript module pattern implementations [duplicate]

This question already has answers here:
Location of parenthesis for auto-executing anonymous JavaScript functions?
(4 answers)
Closed 9 years ago.
Is there any differences between javascript modules:
(function(){}())
vs
(function(){})()
First from book "good parts" by Crockford.
Second is code generated with Typescript.
There is no different. Also you can write the third option if your function doesn't return any value
!function(){}()
No, there is no difference between those two functions and how they're called. In both cases, you're creating an anonymous function and executing it immediately.
The only reason the "outer" parens are required is that when the JavaScript parser is expecting to see a statement, if it sees function it assumes what follows will be a function declaration. But we want to give a function expression, so by giving it an initial (, we put it into a state where it's expecting an expression.
But where the () to call the function go (after the } or outside the wrapping parens) doesn't make any difference.
No there is no difference, they both work the same. I tend to use the latter... it just seems to make more sense. (function(){}) defines the function and then you call it with (). In either case though, use a (leading)semicolon before the first (. Reference

Categories