function ()() in javascript - javascript

I am not sure how to call/frame this question title, but can anyone explain me what does the below code do?
var routes = require("./routes/routes.js")(app);
I am seeing a second () with app being passed, what does that do?
https://github.com/couchbaselabs/restful-angularjs-nodejs/blob/master/app.js
To my surprise, in the code above the variable routes is not at all used in app.js? what's the purpose. I am quite confused here does (app) argument do anything magic here?

The construct
foo()();
expects that foo() returns a function and calls it immediately. It's equivalent to the more readable:
var func = foo();
func();
A similar construct you'll often see is:
(function() {
// function definition
})(args);
This defines a function and calls it immediately. The primary use is to emulate block scope for variables.

Related

Why Javascript import function returns undefined

i want to understand a little bit more about the javascript reference scope, i was trying to import a function from onother file like this
file1.js
exports.checkIfCan = function(){
//make some check
}
exports.calculate = function(){
this.checkIfCan();
}
and using the calculate method with this import
file2.js
const { calculate } = require('./file1.js')
calculate()
actually the error is this.checkIfCan is not a function
but if i import all the module like this it works
const calculation = require('./file1.js')
calculation.calculate();
I just wanna understand more about the global/local scope in javascript
this refers to the context of the function invocation, which in your case is undefined (on browsers the default is window).
Here's an example as simple as possible to make you understand it:
calculation.calculate(); // <= you are calling calculate from calculation, so 'this' is calculation
calculate(); // <= you are calling calculate from... nothing, so 'this' is undefined
Update: using arrow functions it would work either case because this will be taken from the function's surrounding scope instead of the context, and in the top-level code in a Node module this is equivalent to module.exports.
There's a lot to explain about the thisin javascript, may I suggest you read the free ebook You Don't Know JS: this and Object prototypes? You'll find much more information there.
#Vlad Vlads, your problem is in the use of keyword this in your file file file1.js.
In accordance to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this, following behaviour may happen:
The value of this is determined by how a function is
called (runtime binding). It can't be set by assignment during
execution, and it may be different each time the function is called.
With that been said, if you remove the keyword this in your function, following will then works as expected:
const { calculate } = require('./file1.js')
calculate()
Your second example will also works as expected
const calculation = require('./file1.js')
calculation.calculate()
You should use import instead:
file1.js
function abc() {}
export {
abc
}
file2.js
import { abc } from 'file1.js';
abc();

Is there any difference in this JavaScript code? [duplicate]

This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 6 years ago.
I have seen various code which is implemented in following two way. I always use the second one (2.). I wanted to know two thing here.
Is there any difference between these two codes?
Which one is the best practice (and why) if any?
1.
(function () {
//some code here, angular code
})();
2.
(function () {
//some code here, angular code
});
Please also suggest me some good blog or book in this regards as I wants to learn in more detail. Thank you all advance..
Yes, you are not executing the second one.
In the first example, you are declaring an anonymous function, which gets run afterwards with no parameters.
In the second example, you are just declaring it, but not running it.
() is what makes it run, in this case by passing it no parameters.
This one executes the anonymous function:
(function () {
//some code here, angular code
})();
This one doesn't execute it:
(function () {
//some code here, angular code
});
For example, if you have a parameter, you can pass it like so:
(function (c) {
// c.log() is same as console.log
c.log("hello");
})(console);
Note: I've added the parameter example because it's less obvious without any parameter.
Edit:
As #Osman has just pointed in the comments, the first one is known as IIFE.
This pattern is so common, a few years ago the community agreed on a
term for it: IIFE, which stands for Immediately Invoked Function
Expression.
The second is declaration, the first is declaration and execution.
Difference:
The first one executes the anonymous function expression:
(function () {
//some code here, angular code
})();
The second one doesn't execute it:
(function () {
//some code here, angular code
});
anonymous function is a function that doesn't have a name.
Background:
Basically, first we are wrapping the anonymous function declaration with first brackets, like: (), to make it a function expression:
// this is a function declaration:
function () {
//some code here
}
// this is a function expression
(function () {
//some code here
});
By itself it does nothing, as we are neither executing it, nor declaring it within the current scope. In other words, it's useless. Learn more about the difference between function declaration & function expression.
Now, we can use the function expression as a parameter to some other function, like jQuery does:
// now jQuery is taking the function expression as parameter
$(function () {
//some code here
});
Or, we can execute the function itself by using () at the end (This is how we invoke any function actually - in this case without any parameter):
// Now the function expression gets executed.
(function () {
//some code here, angular code
})();
This is also known as Immediately-Invoked Function Expression or IIFE.
The above examples don't have any parameter. However, if you have a parameter, you can pass it like so while executing:
(function (c) {
// Here c.log() is same as console.log()
c.log("hello");
})(console);
Note: I've added the parameter example because it may be less obvious without any parameter.
Best Practice:
Since functionally they are different, the question of best practice doesn't appear. Usually we use IIFE in cases where we want to execute something in a scope different from the current scope & we don't want to leave any footprint of function declaration, variable declaration etc. within the current scope.
Further Reading:
More discussion about this can be found in the following links:
What is the (function() { } )() construct in JavaScript?
What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?
What is the purpose of a self executing function in javascript?
You Don't Know JS: Scope & Closures.
The first one is an IIFE (Immediately-invoked function expression ) as others said, for more info on IIFE check this repo by Kyle Simpson (author of You don't know JS)

Since function expression and function declaration basically do the same thing, when should I use which?

As the question suggest, when should I use
Example A (function declaration):
function abc(){
// some code
}
abc();
over Example B (function expression):
var abc = function(){
// some code
}
abc();
and vice versa.
I know they are different in nature but they basically just do the same thing (correct me if they're not), right?
So how to I decide which one should I use?
EDIT :
I know for Example A, the function can be called whenever wherever intended due to hoisting.
What I actually want to know is what makes you decide to use Example A or Example B.
If you want to call abc() before defining the function, only the first pattern will work.
The variable declaration does get hoisted, too, but not the assignment, so it will be undefined, whereas the function will already be complete with its body.
I guess I would use the var pattern only if I intend to re-assign it later.
Generally, you should use the function declaration syntax when possible. The best reason is that if you define the function in the code after its use, the code will still work.
stuff();
function stuff() {
console.log("hello");
}
will work, but
stuff();
var stuff = function() {
console.log("hello");
}
will not.
When you are passing an anonymous function to another function, you use a function expression.
doSomething(function() {
console.log("done");
});
Otherwise, both work.

Is there another way to write a function declaration?

It just seems odd to me to write dbr.onsuccess after dbr has been declared.
var dbr = window.indexedDB.open("Matrix");
dbr.onsuccess = function(myEvent) {}
Q: Is there an alternative way to write line 2 (without being Rube Goldberg)? Maybe something like:
function dbr.onsuccess(myEvent) {
}
I'm just concerned about the order of things. To me, it seems that it's too late to assign an onsuccess function to dbr after it's been created.
var dbr = window.indexedDB.open("Matrix");
is an asynchronous request.
Async requests run in the background and won't run their callbacks until the function completes. So all of the other assignments will happen before any callback functions are run.
The indexedDB is returning you an interface object so that you can define exactly what those callback functions are. You can think of it as you making a request
Hey I want to open matrix
and getting a response back saying
Hey, I'm working on that, here's an object. Please list what you want to have happen when I finish on it.
Then, when it has completed the open operation (and the current function context has completed running) it will look at that object and run accordingly.
The return value of open isn't the real result of the function, its just an object returned for you to tell it what to do. This is similar to a promise/deferred way of doing things, which is different from the normal JS callback model.
This:
function dbr.onsuccess(myEvent) {
}
is not valid syntax. You can't define a property on an object till the object itself has been defined, and javascript doesn't support function declarations for properties. They're only used for top level objects.
dbr.onsuccess = function(myEvent) {}
This is technically a function expression, as it's an assignment statement to the onsuccess property of dbr.
So when you ask if there is more than one way to write a function declaration, the answer is technically no.
A function declaration has only one form:
function foo() {}
Your suggested syntax to declare a function as a property of an object is interesting but a wrinkle in the idea is function hoisting. As you probably already know, functions (including their definitions) available anywhere within scope, even preceding code. Take this example:
foo.bar();
var foo = getFoo();
function foo.bar() {}
Due to function hoisting, foo.bar should be available on line 1. But due to variable hoisting, foo is declared but not yet defined. On line 1 foo has a value of undefined and would result in a TypeError if you tried to invoke function foo.bar.
I think you can say:
var dbr = window.indexedDB.open("Matrix").onsuccess = function(myEvent) {}

Any reason to have a function as a variable?

Editing someone else's code, I ran across a pattern I had not previously seen:
var functionName = function functionName(){};
and sometime later, to call the function, using this jQuery
$(functionName);
Now, before I change it to the standard function functionName(){} called with functionName();, is there any reason to do it the other way?
EDIT: Updated to reflect the use of jQuery in the function call. I oversimplified the example. (Oops! Sorry!)
var workerFn = function someDefaultFn() {};
if ( lots of logic) {
workerFn = function specialFn() {};
}
//// later on
workerFn();
So now we have flexibility as to what exactly is invoked. Sort of a poor-man's polymorphism.In your example we'd be passing the workerfn to JQuery to be invoked, so same possibility for flexibility.
The only technical reasons for using a function expression would be to avoid hoisting of the function and/or being able to use another internal name to refer to the function itself.
These are the only differences between function expressions and function declarations and it depends on the context whether they are relevant at all.
I'd say it's a bug because functionName; will not do anything. Or is it a typo in your question?
functionName;
would not call the function. This is just a reference to the function. Calling the function needs the (). So if we have
var functionName = function test(){ alert("0");};
this
functionName;
does not call it. Actually this does not do anything at all (no-op). This is same as
var x;
x;
Only this
functionName()
calls it.
Maybe the functionName; is used for something else. We can tell only if we have context.
[EDIT]
You can find var functionName = function(){}; and make as many instance this way var second = functionName;
It's helpful only if you want to have few variables to call the same function, but with a different param...
But in your case, functionName will contain only that the function functionName() {}; will return.
You propably have something like this in the function content:
var functionName = function test(param) {
[...]
return function(otherParam) {
//do something
};
}

Categories