strange way of passing arguments in express.js source code - javascript

When I was looking for source code of express router i saw this:
var debug = require('debug')('express:router:route');
can someone explain what this way of passing arguments mean?

In Javascript, functions are "first class", meaning they can be passed around like any other values.
require('debug') returns a function. As in, the default export of the debug npm package is a function, not an object.
That function is then called with the string "express:router:route"
A function that takes in some state or config, and returns a function based off that state or config, is partial application. This isn't a case of partial application, though, it's just a shorthand for:
var debug = require('debug');
debug('express:router:route');
require isn't a function that's meant to be partially applied, it just means that the debug package is returning a function, and it's being executed in place.

This is a technique as a part of functional programming, called currying, where the function has two arguments, and you can pass the first one and the second one separately.
It is a little hard to get your head around, but worth studying
What is Currying?
Currying is a process in functional programming in
which we can transform a function with multiple arguments into a
sequence of nesting functions. It returns a new function that expects
the next argument inline. It keeps returning a new function (that
expects the current argument, like we said earlier) until all the
arguments are exhausted. The arguments are kept "alive"(via closure)
and all are used in execution when the final function in the currying
chain is returned and executed.
More info here: https://blog.bitsrc.io/understanding-currying-in-javascript-ceb2188c339

Take a look at the debug package (link):
debug exposes a function; simply pass this function the name of your module, and it will return a decorated version of console.error for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole.
So, require('debug') returns a function. That function can be called by doing require('debug')(some parameter). Which means the following is possible (example taken from the debug docs linked above):
var debug = require('debug')('http')
Now the variable debug points to the result of calling the function returned require('debug'), with the parameter 'http'.

Related

Callback function missing scope for required data

I have a issue with a callback function's variable losing its scope
.
I have the following 2 objects in an array(simplified down to show the problem)
const search = [{socket: new WebSocket('ws://live.trade/123')},
{socket: new WebSocket('ws://live.trade/xyz')}];
I then do a forEach on them in an attempt to log the sockets url once the socket is open.
search.forEach(function(element){
element.socket.on('open', function open() {
console.log(element.socket.url);
});
});
*actual output*
ws://live.trade/xyz
ws://live.trade/xyz
*expected*
ws://live.trade/123
ws://live.trade/xyz
I feel like the reason is that when the function open() runs element is not in scope and it just uses whatever was last there(being the ws://live.trade/xyz).
Is this correct? And finally what would be the way to go about fixing this? The real use for this is when the socket is opened I need to send version data to the server via the socket that called it... Im going to have many sockets in reality and dont want to write a "socket.on('open'...)" for each individual one.
Any suggestions?
Thanks so much!
Your callback (i.e. in socket.on()) uses the element variable of the forEach(). From your actual result, it could mean that:
1. Scope issue
The variable could be "overriden" over the iterations because of javascript/node scope mechanism, it is not the case with the code you gave but it is a common issue working with scopes inside loops.
in this case you would have to do :
search.forEach(function(element){
element.socket.on('open', function(){
console.log(this.socket.url);
}.bind(element));
});
Explanation:
bind() passes its first argument (the element variable in this case) to the anonymous function as this inside it.
Inside your callback function, this.socket is equivalent to element.socket at the appropriate iteration
[UPDATE] after pointed out by Felix Kling, forEach() provides a scope for each element.
See bind for more details.
2. Dependency issue
If it is not a scope issue, it could mean that the library you are using does not work as expected. Maybe, try to log element inside the forEach() to check if the WebSocket objects are what you expect.
edit
For further reading on node/js loops and reference: see here
For node/js closures in general: see here

CLI NodeJS (Concurrency, Callbacks, .methods)

Just a couple of questions regarding using Nodejs in Web Development.
1) For my Concurrency question, it regards syntax. Is there a difference between:
setInterval(function() {
console.log('Task A');
}, 10);
and
function setInterval() {
console.log('Task A');
}, 10);
Also, i'm a little confused what the '10' means at the end of the method, my guess is the time it takes for the method to complete?
2) Callbacks - Are Callbacks just technically another name in Node for testing code?
3) Is there a method I can use in the Node(CLI) to see all of the methods in a module?
EX:
var fs = require('fs');
Obviously there are tons of methods in the File Systems module, but like the language Ruby, using PRY in the CLI, you can type 'fs.methods', which will display all of the methods. Then using 'cat', you can see the contents of each individual method. Something like this for Node(CLI)?
Thanks for all of the advice/answers!
Cheers,
G
1.
In the first, you pass in an anonymous function which will be invoked at the interval. Here you are using the node.js API setInterval.
In the second example, you are declaring a function called setInterval. Looks like a syntax error is there...
setInterval is a function that takes 2 objects in as parameters. That's it. the first parameter should be a function, and the second parameter should be a the the interval time in milliseconds. All that setInterval does is run the function passed in in the first parameter(a callback) every x milliseconds as specified in the 2nd parameter.
2.
No. Callbacks are functions that can be passed to other functions so that they can be "called-back" later in the code. Callbacks are pervasive in node.js applications and tightly related to it's asynchronous event based architecture. It is one of the most common patterns seen in node.js.
3.
Just look in node.js api docs on their website.
My recommendation to you would be to read about the node.js event loop and asynchronous programming.
First off, you're asking about some pretty fundamental aspects of Javascript so I'd suggest you work though some basic Javascript training because it will be hard to learn node.js if you don't already have a core understanding of the basics of Javascript. In particular callbacks are integral to much of nodejs coding.
Is there a difference between these two?
Yes, the two are completely different. One uses a built-in timer function, the other attempts to declare it's own function that has nothing to do with timers.
Let me explain your two examples:
The built-in setInterval function
setInterval(function() {
console.log('Task A');
}, 10);
Nodejs has a built-in timer function called setInterval. You can find the doc for it here.
You pass this function two arguments. The first argument is a function reference, the second argument is an amount of time in milliseconds. The nodejs timer infrastructure will call the function you passed it every N milliseconds.
It might be slightly easier to understand how setInterval works by seeing it used like this:
function myFunction() {
console.log('Task A');
}
setInterval(myFunction, 10);
This has the same output as your first example, but I think it shows more clearly how setInterval() is a built-in function that takes two arguments, a function and a number.
In your example, instead of the named function you are passing an anonymous function that simply does console.log('Task A'); and that function will be called every 10ms (approximately).
Create Your Own Function
function setInterval() {
console.log('Task A');
}, 10);
This block of code is a Javascript Syntax Error and will not work. It looks like you're attempting to define your own function called setInterval(), but this is not the proper syntax for declaring a function.
You could make it legal syntax like this:
function setInterval() {
console.log('Task A');
}
And, then you would call it like this:
setInterval();
This has nothing to do with the previous example. This just creates a function that runs once each time you call it. If you actually gave it the same name as the global function setInterval(), then your local definition would replace it within the scope it was declared.
Your Other Questions
Also, i'm a little confused what the '10' means at the end of the
method, my guess is the time it takes for the method to complete?
The 10 in the first example is the number of milliseconds for the interval timer. The 10 in the second example does not belong there - it's part of a Javascript syntax error.
Callbacks - Are Callbacks just technically another name in Node for
testing code?
No. A callback is when a function takes an argument that is a function reference (e.g. the name of a function or an anonymous function). When you pass a callback to this function, you can expect that the function will call the callback one or more times at some time in the future. When exactly it is called or how many times it is called depends entirely upon what the function does and how it is written. The term "callback" comes from the notion that this function will be "called back" some time in the future.
Is there a method I can use in the Node(CLI) to see all of the methods
in a module?
I'm not aware of a specific feature in the command line interface that will give you the methods of a module, but you can iterate them yourself or look at them in the debugger.
When you load a module in node with something like:
var fs = require('fs');
The object you get back from the require() function is a Javascript object. All the methods of that module are properties on that object. You can inspect that object in the debugger or with console.log(fs) or by writing code to iterate the properties of that object.
var fs = require('fs');
for (var prop in fs) {
if (fs.hasOwnProperty(prop)) {
console.log(prop);
}
}

How does "makeAddFunction" in Eloquent JS work?

I'm trying to learn Javascript by reading Eloquent Javacript. I'm on the chapter dealing with functions and I'm stuck trying to figure out how the code below works. I don't see how the add function ever gets called. I see them calling addTwo and addFive but those names are different than add. The result of this code being run is 9. Can someone please explain this to me.
function makeAddFunction(amount) {
function add(number) {
return number + amount;
}
return add;
}
var addTwo = makeAddFunction(2);
var addFive = makeAddFunction(5);
show(addTwo(1) + addFive(1));
In makeAddFunction, a function is created, called add. This function is returned.
makeAddFunction is called twice with 2 different parameters, and stored in two variables, addTwo and addFive.
Calling addTwo() and addFive() is calling the functions created by add(), with the "amounts" 2 and 5 respectively.
addTwo(1) + addFive(1) == (1 + 2) + (1 + 5) == 9
Sometimes these types of 'closures' are called Builders, or Factories. The makeAddFunction 'builds' a special version of add based on the parameter you pass to makeAddFunction.
The addTwo function would look like:
function addTwo(number) {
return number + 2;
}
The makeAddFunction create a closure that sets amount as whatever number you pass in and returns a function that will add that amount to whatever number you pass to the new function and return it.
My best advice is you try to learn a bit about Javascript closures. Really. I might not be the answer you are looking for, but it is the best you can do if you want to understand what's happening there.
Get yourself a copy of any good javascript book. Let me suggest 'Javascript - The Good Parts' by Douglas Crockford.
For some of us, Javascript closures were not something we grokked. I hope it's easier for you.
Anyway, makeAddFunctionis a function creator. It creates new functions which are tied to the parameter you passed to makeAddFunction. Therefore, the addTwo variable receives and stores a new function, which you can invoke later by appending parentheses to it, i.e. addTwo().
The parameter you pass to addTwo, i.e. 1on invokation addTwo(1) is passed to the add function, because addTwo is nothing more than an add function where the amount var has a fix value of 2.
var addTwo = makeAddFunction(2);
When you call makeAddFunction(2) initially, the amount var is within its function scope where add can see it. addTwo now is set to the add function that makeAddFunction(2) returned.
addTwo(1)
Remember addTwo is now set to what makeAddFunction(2) returned, which is the function add, and amount is set to 2 within makeAddFunction(2)'s scope. add just returns its argument (1), plus the amount (2) in makeAddFunction(2)'s scope.
The same goes for addFive(5).
Javascript Ninja or The Good Parts are good reads that explain closures in detail. I'd highly suggest picking up those.
Follow the SO Linked/Related Questions on the right. Anyway ..
This is explained the article, albeit with a lot of fluff. Anyway, with a bit of fluff-cutting here is a "annotated" version:
.. functions [do] not just package up [some code to run], but also an environment. [..] a function defined inside another function retains access [to lexical variables (like "amount")] that existed in [the outer function] at the point when [the inner function] was defined.
Thus, the [inner] add function in the above example, which is created when makeAddFunction is called, captures an environment [including the "amount" variable of the outer function]. It packages this environment, together with [the code to run], into a value [(which is a fancy way to say functions are just objects)], which is then returned from the outer function.
When this returned function ([which has been assigned to] addTwo and addFive) is called, [the called function has access to] the captured environment ([and the "amount" variable which still contains the value initially passed to makeAddFunction]). These two values ([which are currently named by] "amount" and "number") are then added, and the result is returned.
I am not found of the original usage of "value" and have edit those parts a good bit - in JavaScript, variables (not values) are bound in closures.
Javascript relies pretty heavily on higher-order functions. Functions can be returned, assigned to variables, and passed around as values. This comes in handy in a lot of situations, especially when dealing with evented programming (JS's direct lineage from the its most prolific implementation in the browser.)
http://en.wikipedia.org/wiki/Higher-order_function
What you are seeing is a function that creates a function. It could be considered a "factory" for a function with one preset argument.

What is an immediately executed factory function in the context of JS module loading?

In the Require.js documentation, in the section called Why AMD, the following is asked:
How are pieces of JavaScript code defined today?
Among other answers is the following:
Defined via an immediately executed factory function.
I understand (at least I think I do) that a javascript factory function is simply a function that returns a new instance of an object, but I don't understand what this means in the context of this question. Can someone explain this?
My guess is you are not clear about the different between a javascript "factory function" and a constructor function. I usually see the phrase "immediately-invoked function expression" or IIFE as per Addy Osmani's book or this article, but I believe IEFF is a reference to the same structure. In IEFF (using their terminology) has this basic formula:
(function () { return {};})();
It's basically a javascript pattern (/hack) used to create a function scope and thus give you control over exposing some but not all of the objects within that scope to the caller. Don't get "factory function" confused with a constructor function. You don't use the new keyword with an IIFE, but you do with a traditional javascript constructor function. Constructor functions are about creating object instances and typically you will create many instances, each with unique state. Factory functions help create cleanly encapsulated modules and typically you only need to invoke it once and get a reference to a single module instance for you entire application lifetime.
You can see the following sample code at Why AMD
(function () {
var $ = this.jQuery;
this.myExample = function () {};
}());
This is an example of immediately executed factory function. So this function will execute at the time of interpretation. And we should consider loading of JQuery before this example[because it is using JQuery]. That is the job of RequireJS to load required JavaScript files as per our order.

Understanding jquery source code

I have recently started to delve deeper in to JavaScript and have come across this code construct in JQuery.
(function( window, undefined ) {
})(window)
Reading on stack overflow (and elsewhere) I have come to the conclusion that this is the same as
function foo(window, undefined) {
...
}
foo(window);
Am I correct in my assumption?
If so, what are the advantages of the former? (other than confusing newbs)
There are several things you need to know to make sense of it:
It is an anonymous function, which simply means it does not have a name.
The function is called immediately after it is declared. You see the open parenthesis on line 2, immediately after the function definition? That means, "call this function".
Only one parameter is passed to the function. That parameter is "window", which is the name of the global scope inside of a browser.
The function being called actually expects *2* parameters, but we're calling it with one. Javascript lets you call functions with more or fewer parameters than the function actually expects. There are ways of getting to the list of parameters that was passed.
Since we are only passing one parameter, the second parameter will automatically be set to "undefined". "undefined" is a special javascript value that means, get ready, "undefined".
It just so happens that we have also named our second parameter with the name "undefined". So in effect, we have created a local variable (parameters are very much like local variables) that is named undefined, and whose value is undefined.
Why on Earth did we do that? It is a way of ensuring that, within our anonymous function, if we refer to "undefined", it really will have the value of "undefined". If we didn't do that, and some crazy code outside of our scope redefined "undefined" (by saying something like "undefined = 42"), then we'd write code thinking we were referring to undefined but we'd actually be referring to 42. These shenanigans with passing 1 parameter but expecting 2, and calling the second one undefined, protects us from such nonsense.
I hope that's clear, let me know if it is not. I learned all that from Paul Irish's video mentioned above.
This is an anonymous function. It is created and then goes out of scope, which here is the advantage. It is created and instantiated immediately. What is good about this is that it is not going to collide with any function on the global namespace, and thus will not obliterate anything you may have included on the page.
It is an anonymous function, it has quite a few benefits, like being only active in the current scope. You can read more about it here.

Categories

Resources