What is the difference between two declarations of module in javascript? - javascript

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.

Related

What does placing parenthesis alone around a function mean? (function(){})

I know what an Immediately-Invoked Function Expression is. I know the difference between this
let x = function()
{
}
and this
let x = (function()
{
})()
but what about this
let x = (function()
{
})
do the parenthesis here have any significance alone? I've seen it in several places before.
I thought this was an example but it might not be one X)
edit: Those weren't really intended to be code snippets, anyhow assuming they're snippets, it turns out there's big difference between the case where they are function declarations and function expressions. I didn't expect this. Sorry for the context change and thanks for all the care!
Answer to the edited question:
but what about this
let x = (function()
{
})
There is no purpose served by those () at all. That's exactly the same as:
let x = function()
{
}
Answer to question embedded in comments:
In a comment you've said you actually were wondering about this:
let foo = () => ({ bar: { foo: 1, bar: 2, } });
The () are necessary because that's an arrow function with a concise body returning the result of an object initializer. But if there's a { immediately after the =>, the { would be the opening of a block (verbose) body instead (not the beginning of an object initializer). That's why the () are necessary around the expression body of the concise arrow, to disambiguate the {.
Note that the () are not around the function; just its body.
You can write it the way you did:
let foo = () => ({ bar: { foo: 1, bar: 2, } });
or with {} and return:
let foo = () => { return { bar: { foo: 1, bar: 2, } } };
but not:
let foo = () => { bar: { foo: 1, bar: 2, } }; // Wrong
because the { would be read as the beginning of a block body.
Answer to original question:
I'm going to assume these have names, as otherwise your first example is a syntax error.
but what about this
(function()
{
})
That would be a function expression that isn't immediateley invoked. Unlike your first example, it's evaluated when the step-by-step execution reaches it, instead of when the context it's in is initially created.
Unless something is using the result of that expression, it's a no-op (something that does nothing), since nothing in the expression runs it.
If the result of the expression is being used (it's the right-hand side of an assignment, it's being passed into a function as an argument, etc.), the () around it are unnecessary with a function expression. (That isn't always the case with an arrow function.)
Given the original question:
All else being equal (and it probably isn't because you omitted the context):
This is a syntax error. It starts off as a function declaration and then doesn't meet the syntax requirements.
This is an immediately invoked function expression.
The parenthesis make this a function expression (just like in example 2). It isn't invoked (the () are missing at the end). It isn't assigned anywhere. It does nothing.
But now you've rewritten the question and completely changed the meaning.
Example 3 and Example 1 are now the same.
Putting ( and ) around an expression does nothing except override operator precedence … and there are no operators inside them.
There's no difference between (function() {}) and function() {}.
This lines are also the same :
var test1 = (function() {});
var test2 = function() {};
BUT, if you only write this :
function() {};
You'll get a syntax error. If you don't want a syntax error you have to write this :
(function() {});
But this line is useless and do nothing at all. Because the defined function is never called and no one can access it.
Enclosing a function in parentheses in this way lets you package it for use in another variable or function.
For example, you could use this (somewhat redundantly) to set a variable to a function.
var foo = (function bar() { /* code */ });
foo(); // calls code in bar()
This is also a way to package a callback function, e.g.
asyncFunction((function callback() { /* code */ });
You wouldn't want to use this type of declaration on its own because it becomes hidden to the rest of your code as in the below example.
function foo() { /* code */ };
(function bar() { /* code */ });
foo(); // runs foo code
bar(); // ERROR - bar() undefined in this scope
A similar syntax is used with a trailing parentheses in an "Immediately-Invoked Function Expression". This passes a variable into your function and runs it inline.
(function foo(a) { console.log(a) })("Hello World!");
// Prints "Hello World"
TL;DR - Use it as a way to write a named function inline and package it into another function or variable or, with trailing parentheses, to call your function immediately with a specified input.

JAVASCRIPT functions knowing about other functions

Is javascript code read from the top down?
In other words if I have:
function Color(){
}
function Weather() {
}
If I wanted to incorporate some type of weather object inside the Color function would it be possible since Weather is defined afterwards?
The function Color won't know about Weather as it's being parsed, but it will once it is called. For example:
// Since variable declarations are hoisted to the top,
// myVar will be undefined (same as simply saying "var myVar;")
console.log(myVar); // <-- undefined
var myVar = 5;
console.log(myVar); // <-- 5
// test2 hasn't been defined yet, but it doesn't matter
// because test isn't being executed
var test = function() {
test2();
}
// This will throw an error: undefined is not a function
// because test2 isn't defined
test();
var test2 = function() {
alert("test2");
}
// This won't throw an error
test();
Essentially, you should execute after all functions have been defined. However, if you use the function functName() {} syntax, then it is hoisted just like a var statement.
function test() {
test2();
}
// Works!
test();
function test2() { alert("test2"); }
JavaScript is parsed "top-down" and Function Declarations are hoisted constructs - see var functionName = function() {} vs function functionName() {}. Parsing happens before the JavaScript execution itself starts; the following thus covers the evaluation semantics1.
Given the effect of function hoisting, the following code is valid, although it seems like it might not be:
function a(){
return b();
}
alert(a()); // alerts "b", even though "b comes later"
// This declaration IS hoisted
function b() {
return "b";
}
However, considering that even when using "var fn = .." (when the assignment is not hoisted) the ordering usually doesn't matter because the evaluation of the assignments happens before the usage:
var a = function () {
return b();
}
// alert(a()); <- this would fail, because b is not assigned yet
// This assignment is NOT hoisted
var b = function () {
return "b";
}
// But b is assigned before here, meaning that the order of the constructor
// functions still Just Doesn't Matter.
alert(a());
As such, in the case where there are two constructor functions (e.g. Color and Weather) which are [mutually] dependent, it doesn't matter where they are located in the same scope relative to each other.
1The thing that matters is the expression representing the dependency is resolvable when evaluated (which is relative to the evaluation code, but not related to the parsing/placement order of the functions).
so basically yeah you can implement something to a function that appears in a previous code.
hole this helps you understand it better.
var weather = function() {
if (weather === red) {
console.log("weather is represented by the color red");
}
else {
console.log("Not the right color");
}
};
weather(red);

javascript (function(window){})(window)

The code in https://github.com/mattdiamond/Recorderjs/blob/master/recorder.js
I don't understand the javascript syntax like
(function(window){
// blah-blah
})(window)
When I tried the code follow, I could see "hello world" in the console.
(function(window){
console.log("hello world");
})(window)
What does this mean?
Any references?
Thanks in advance
What does this mean? Any references?
It simply executes the bracketed function, just as if it's splitted as:
f = (function(window){
console.log("hello world");
})
f(window)
In any JavaScript file if you write something like:
justFunction();
//function declaration
function justFunction()
{
alert("something");
}
This will call the justFunction() and show an alert. Defining a function like that is known as function declaration.
Now there is another way to define a function
var anotherFunction = function() { alert ("something")}
Now if you write something like
anotherFunction();
// Function Expression
var anotherFunction = function() { alert ("something"); }
Although anotherFunction is a function here this will give an error in console. This is known as function expression.
The reason behind that is function declarations loads before any code is executed. While function expressions loads only when the interpreter reaches that line of code. So if you try to call a function expression before it's loaded, you'll get an error.
But if you call a function declaration, it'll always work. Because no code can be called until all declarations are loaded. So you will have to always call the function expression after it is defined.
// Function Expression
var anotherFunction = function() { alert ("something"); }
anotherFunction();
Now a function expression can be called immediately by adding parenthesis after the anonymous function like
var anotherFunction = function() { alert ("something"); }(); //paranthesis added
This code snippet and the above does the same thing (shows the alert). Now the anotherFunction variable is not the same as above because it is now assigned with the value , that the anonymous function will return. Right now it is not returning anything so anotherFunction is undefined. So if you write something like
var anotherFunction = function() { alert ("something"); }();
anotherFunction(); //error
This will give an error, because the anonymous function does not return any function. If its returns something like
var anotherFunction =
function() { alert ("something"); return "some string"; }(); //returns string
anotherFunction is now a string variable. And if:
var anotherFunction = function() { alert ("something"); return function(){
alert("somethingElse")
}; }(); // returns function
Now anotherFunction is a function and can be called like anotherFunction().
You can pass parameters to this function expression like
var anotherFunction = function(p1,p2) { console.log(p1);
console.log(p2); }(param1,param2 ); //param1,param2 are parameters
One of the main difference between a function expression and a function declaration is that A function expression can be called (invoked) immediately by using a set of parentheses, but a function declaration cannot be.
Now if we don't want to assign the function expression to a variable, then we have to write it inside parenthesis.
(function() { alert ("something");});
And to call it we need to add another set of parenthesis at the end like
(function() { alert ("something"); }());
And same as earlier, we can also pass parameters to it like:
( function(param){ console.log(param); }(param));
This type of functions are ## Heading ##called IIFE (Immediately Invoked Function Expression).
IFFE is just an anonymous function (no name attached to it) that is wrapped inside of a set of parentheses and called (invoked) immediately.
( function(){ }());
REFERNCE
Consider this example.
var message = 'hello world';
function Say(msg){
console.log(msg);
}
new Say(message);
You can make it self invoking anonymous function by wrapping the Say() without a name with parentheses and adding another parentheses after it and pass the message to it.
(function(msg){
console.log(msg);
})(message);

Very basic Javascript constructors problem

In the following JavaScript code main() is called.
My question is why the second constructor is called rather than the first one ?
What am I missing here ?
Thanks !!
function AllInputs() {
alert("cons 1");
this.radioInputs = [];
alert(this);
}
function AllInputs(radioElement) {
alert("cons 2");
this.radioInputs = [radioElement];
alert(this);
}
AllInputs.prototype.toString = function() {
return "[object AllInputs: radioInputs: " + this.radioInputs.length + "]";
}
function main() {
var result = new AllInputs();
}
Javascript does not support overloaded functions.
When you define the same function twice, the second definition replaces the first one.
Instead, you should make a single function, and check arguments.length to see how many arguments were passed.
For example:
function AllInputs(radioElement) {
this.radioInputs = arguments.length ? [radioElement] : [];
alert(this);
}
In JavaScript, the last definition of an identifier is used:
function foo() { return "bar"; }
var foo = "foo";
alert(foo);
In that case, foo was a variable with the value "foo". Had foo been a function, it would have simply said that foo was a function. If you don't believe it, try using alert(foo()) instead of just alert(foo). You'll most likely get an error in your console log with no visible output like you had with alert(foo) (the variable...not the function call).
function foo() { ... }
is really just shorthand for
var foo = function () { ... }
Hence, the second time you're declaring the function, you're overwriting the variable AllInputs with a different function. There ain't no such thing as two functions with the same name in Javascript, since all functions are really variables.

What is the difference between these two functions/approaches?

I use only jQuery for writing JavaScript code. One thing that confuses me is these two approaches of writing functions,
First approach
vote = function (action,feedbackId,responseDiv)
{
alert('hi');
return feedbackId;
}
Second approach
function vote(action, feedbackId,responseDiv)
{
alert('hi');
return feedbackId;
}
What is the difference between the two and why should one use the first approach or the second approach?
The first is a function expression assigned to the vote variable, the second is a function declaration.
The main difference is that function statements are evaluated at parse time, they are available before its declaration at runtime.
See also:
Named function expressions demystified (article)
Explain JavaScript’s encapsulated anonymous function syntax
function myFunction() {}
...is called a "function declaration".
var myFunction = function() {};
...is called a "function expression".
They're very similar; however:
The function declaration can be declared after it is referenced, whereas the function expression must be declared before it is referenced:
// OK
myFunction();
function myFunction() {}
// Error
myFunction();
var myFunction = function() {};
Since a function expression is a statement, it should be followed by a semi-colon.
See Function constructor vs. function declaration vs. function expression at the Mozilla Developer Centre for more information.
The function declaration syntax cannot be used within a block statement.
Legal:
function a() {
function b() {
}
}
Illegal:
function a() {
if (c) {
function b() {
}
}
}
You can do this though:
function a() {
var b;
if (c) {
b = function() {
};
}
}
The first one is a function expression,
var calculateSum = function(a, b) { return a + b; }
alert(calculateSum(5, 5)); // Alerts 10
The second one is a plain function declaration.

Categories