This question already has answers here:
Are "(function ( ) { } ) ( )" and "(function ( ) { } ( ) )" functionally equal in JavaScript? [duplicate]
(3 answers)
Closed 8 years ago.
We can have immediately invoking function in two ways. I am confused about what is the difference between the following
var foo = function(){
return { };
}();
and this :
var foo = (function(){
return { };
}());
Exactly the same.
// This one creates a function expression, then executes that function expression.
var foo = function(){
return { };
}();
// This one creates a function expression, inside of a set of parens.
// the parens hold an expression.
var foo = (function(){
return { };
}());
The parens are used for two reasons:
1) In this context, they are a clue to the READER, not to the compiler, that you have an IIFE.
2) In other contexts, the parens force a expression, when a function statement might be generated.
// The parens here force an expression, which means it forces a function expression
// instead of a function statement.
(function () {....})
Related
This question already has an answer here:
Why doesn't my arrow function return a value?
(1 answer)
Closed 5 years ago.
Is there any difference between returning a value in an arrow function, vs adding the body and typing return?
As far as I'm aware they are the same.
Here's a session:
let a = () => 1;
a()
1
let b = () => { return 1; }
b()
1
a
() => 1
b
() => { return 1; }
Is there any situation when these are different?
One difference is that returning object literals using the implicit return syntax requires the object literal to be wrapped in parenthesis.
var foo = () => { bar: "foobar" }; //This function returns undefined
var foo = () => { return { bar: "foobar" }; }; //This function returns an object
var foo = () => ({ bar: "foobar" }); //This function returns object
As far as I'm aware, this is the only difference.
concise body arrow functions implicitly returns value whereas for multi line arrow functions you must explicitly return value.
In your case both will have same net result
This question already has answers here:
What is the purpose of a self executing function in javascript?
(21 answers)
Closed 7 years ago.
I am new to javascript and I might have dove into the deep end first. I have came across the following definition while reading design patterns in js. I don't understand the syntax used here, why is the "log" function definition in "()",
var log = (function() {
var log = "";
return {
add: function(msg) { log += msg + "\n"; },
show: function() { alert(log); log = ""; }
}
})();
Please point me in the right direction.
Without the parenthesis, the right hand side of your assignment is a function expression, and log is assigned a reference to that (anonymous) function expression, allowing to call log() later.
If you include the parenthesis, the wrapped function turns into a self-invoking function expression (and is immediately executed), so log is assigned whatever this function call returns.
As someone else already stated, your code shows an example of the so-called module pattern. Read much more about it here.
I don't understand the syntax used here, why is the "log" function
definition in "()"
Its basically self executing anonymous function. There are several ways of writing such functions.
(function() {
alert('hi there');
})();
! function() {
alert('hello');
}();
+ function() {
alert('plus');
}();
- function() {
alert('minus');
}();
Now such function can also return values:
var msg = (function() {
return 'hello';
})();
alert(msg);
var calc = (function() {
return {
add: function(a, b) {
return a + b;
},
sub: function(a, b) {
return a - b;
}
};
})();
alert(calc.add(4, 5));
This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 9 years ago.
In the Module Pattern example from Addy Osmani, a private function is assigned to a variables as shown in this example:
var myNamespace = (function () {
var myPrivateVar, myPrivateMethod;
// A private counter variable
myPrivateVar = 0;
// A private function which logs any arguments
myPrivateMethod = function( foo ) {
console.log( foo );
};
return {
// A public function utilizing privates
myPublicFunction: function( bar ) {
// Increment our private counter
myPrivateVar++;
// Call our private method using bar
myPrivateMethod( bar );
}
};
})();
I would have simply written the private function as:
function myPrivateMethod( foo ) {
console.log( foo );
};
Is there any reason to assign the function to a variable if it's not used as a delegate? I'm looking at some code that uses this pattern consistently and I'm finding it hard to follow. For example:
var _initializeContext = function() { // many lines of code }
This is a function declaration vs a function expression issue. To some degree it's a stylistic choice. What you do need to be aware of is that function declarations get hoisted by the JS interpreter, which function expressions aren't. Some people prefer to use function expressions because they don't like the idea of their code being rearranged.
You might want to check out:
var functionName = function() {} vs function functionName() {}
http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/
http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html
What is the different between two declarations of a module in JavaScript?
One has parentheses around the function and other one doesn't?
One article says that
Notice the () around the anonymous function. This is required by the
language, since statements that begin with the token function are
always considered to be function declarations. Including () creates a
function expression instead.
Both seem to do the same thing when checked.
var person = (function () {
// Private
var name = "Robert";
return {
getName: function() {
return name;
},
setName: function(newName) {
name = newName;
}
};
}());
var person = function () {
// Private
var name = "Robert";
return {
getName: function() {
return name;
},
setName: function(newName) {
name = newName;
}
};
}();
Functions are of two types in JavaScript - declarations and expressions.
This is the difference between the two:
Function declarations are hoisted. This means you can call the function before it appears in the program as declarations in JavaScript are hoisted.
Function expressions can be invoked immediately. A function declaration cannot. This is because expressions express (or return a value). Function expressions express a function.
An example of a function declaration:
foo("bar");
function foo(bar) {
alert("foo" + bar);
}
The above program will work because foo is a function declaration.
foo("bar"); // throws an error, foo is undefined - not a function
var foo = function (bar) {
alert("foo" + bar);
};
The above program will not work as foo is declared as undefined, hoisted and then later assigned the value of a function expression. Hence it's undefined when it's called.
An example of a function expression:
(function (bar) {
alert("foo" + bar);
}("bar"));
The above function will be immediately invoked as it's a function expression.
function (bar) {
alert("foo" + bar);
}("bar"); // throws an error, can't call undefined
The above function will not be immediately invoked as it's a function declaration. Remember, declarations do not express (or return a value). So it's like trying to invoke undefined as a function.
How does a function become an expression?
If a function is used in the context where an expression is expected then it's treated as an expression. Otherwise it's treated as a declaration.
Expressions are expected when:
You're assigning a value to a variable (i.e. identifier = expression).
Inside parentheses (i.e. ( expression )).
As an operand of an operator (i.e. operator expression).
Hence the following are all function expressions:
var foo = function () {};
(function () {});
~function () {};
Everything else is a function declaration. In short if your function is not preceded by anything, it's a declaration.
See this code: https://github.com/aaditmshah/codemirror-repl/blob/master/scripts/index.js#L94
The following function isExpression is used to test whether some arbitrary JavaScript code is an expression or not:
function isExpression(code) {
if (/^\s*function\s/.test(code)) return false;
try {
Function("return " + code);
return true;
} catch (error) {
return false;
}
}
Hope this clears any doubts in your mind.
In short:
A function expression expresses or returns a value (in this case a function). Hence it can be immediately invoked, but it can't be called before it appears in the program.
A function declaration is hoisted. Hence it can be called before it appears in the program. However since it doesn't express any value it can't be immediately invoked.
In the current context there's no difference for the interpreter. Usually preferable way of writing module is by wrapping the function with parentheses:
var person = (function () {
// Private
var name = "Robert";
return {
getName : function () {
return name;
}
};
}());
That's because the syntax is cleaner and it's obviously that you want to invoke the function immediately after it is declared. One more reason is because:
(function () {
//some stuff
}());
will work but
function () {
//some stuff
}();
this wont.
By wrapping the function each time you use common codding style which is usually a good thing :-).
The difference is that when writing:
var foo = (function () {
...
}());
the use of the (superfluous but useful) grouping () is a common coding style to make it clear from very like first line that the right hand side is most likely an immediately invoked function expression (IIFE). However, in the second:
var foo = function () {
...
}();
it doesn't become apparent until you read the last line, which might be quite a few lines down. Until you reach the last line, you probably thought you were reading a plain assignment:
var foo = function () {
...
};
Note that the parenthesis can be used in a plain assignment too:
var foo = (function () {
...
});
but in that case they really are superfluous (and probably misleading due to the convention of using them for IIFEs).
See An Important Pair of Parens.
This question already has answers here:
Location of parenthesis for auto-executing anonymous JavaScript functions?
(4 answers)
Closed 8 years ago.
Both of these code blocks below alert foo then bar. The only difference is })() and }()).
Code 1:
(function()
{
bar = 'bar';
alert('foo');
})();
alert(bar);
Code 2:
(function()
{
bar = 'bar';
alert('foo');
}());
alert(bar);
So is there any difference, apart from the syntax?
No; they are identical
However, if you add new beforehand and .something afterwards, they will be different.
Code 1
new (function() {
this.prop = 4;
}) ().prop;
This code creates a new instance of this function's class, then gets the prop property of the new instance.
It returns 4.
It's equivalent to
function MyClass() {
this.prop = 4;
}
new MyClass().prop;
Code 2
new ( function() {
return { Class: function() { } };
}() ).Class;
This code calls new on the Class property.
Since the parentheses for the function call are inside the outer set of parentheses, they aren't picked up by the new expression, and instead call the function normally, returning its return value.
The new expression parses up to the .Class and instantiates that. (the parentheses after new are optional)
It's equivalent to
var namespace = { Class: function() { } };
function getNamespace() { return namespace; }
new ( getNamespace() ).Class;
//Or,
new namespace.Class;
Without the parentheses around the call to getNamespace(), this would be parsed as (new getNamespace()).Class — it would call instantiate the getNamespace class and return the Class property of the new instance.
There's no difference - the opening brace only serves as a syntactic hint to tell the parser that what follows is a function expression instead of a function declaration.
There's no difference. Both are function expressions.
There is be a third way, too:
+function() {
bar = 'bar';
alert('foo');
}();
(instead of the + another operator would work, too)
The most common way is
(function() {
// ...
})();
though.