What does this underscore mean in node js - javascript

I saw the following line in a node js code base.
_ => { return resolve(abc);}
Can any one give me some hint on what this _ means?
I know => is fat arrow function. This line is from a snippet of promise.

At the coaxing of a discussion elsewhere in this question, I'll turn my comments into an answer.
First off, I assume you aren't asking about arrow functions in general, but are just curious about the _ in your code sample.
There is a convention (used by some) to declare and name a parameter to a callback function that you know is passed, but you are not going to be using with an underscore as a sort of placeholder. It's a signal to people reading the code that there is an argument being passed to this callback, but you don't plan on using it in this particular invocation. It's presence is not functional, but more for
Now, without knowing what was in the head of the developer who wrote the line of code you asked about, we can't know for sure what the underscore means, but it does appear to match that previously described convention. There is one argument to the callback and it is not used in the implementation of the callback.
So, if our guess that this is a use of that convention is true, then in the arrow function that you show:
_ => { return resolve(abc);}
It is likely expecting one argument, but this particular use of that callback does not plan on using it, thus they named it with an _ just to signal that.
Now, there is no particular reason in Javascript that the callback needs to even define a single argument like this that be used. The callback could just as well have been defined as:
() => { return resolve(abc);}
since there's no requirement in Javascript that you declare arguments you aren't going to use.
If the callback took two arguments and it was the first one that you weren't going to use, then it does have to be declared as something in order to allow access to the second argument:
(_, secondArg) => { return resolve(secondArg);}

It means that the arrow function argument is not used. They use _ as argument name for the arrow function.

Doesn't this mean something like this?
function(_){
return resolve(abc);
}

What's happening here is that the code is using (some of) the concise syntax for arrow functions. To do this you'd write a function like this:
var f = x => x*x;
according to the docs
So with your example, the argument x is named with an _ (a valid character for variable names):
var f = _ => {return resolve(abc)}
But, it doesn't need the return or the brackets, either. It could be just:
_ => resolve(abc);
Perhaps a more readable way to write it would be with the parathesis:
() => resolve(abc);

Related

Meaning of "_" passed as parameter [duplicate]

I was going through the code of one of the chart library written in javascript, wherein I've seen passing underscore(_) as a function parameter. What does that mean?
chart.x = function(_) {
if (!arguments.length) return lines.x;
lines.x(_);
lines2.x(_);
return chart;
};
Can someone please update on this...Thanks.
The underscore symbol _ is a valid identifier in JavaScript, and in your example, it is being used as a function parameter.
A single underscore is a convention used by some javascript programmers to indicate to other programmers that they should "ignore this binding/parameter". Since JavaScript doesn't do parameter-count checking the parameter could have been omitted entirely.
This symbol is often used (by convention again) in conjunction with fat-arrow functions to make them even terser and readable, like this:
const fun = _ => console.log('Hello, World!')
fun()
In this case, the function needs no params to run, so the developer has used the underscore as a convention to indicate this. The same thing could be written like this:
const fun = () => console.log('Hello, World!')
fun()
The difference is that the second version is a function with no parameters, but the first version has a parameter called _ that is ignored. These are different though and the second version is safer, if slightly more verbose (1 extra character).
Also, consider a case like
arr.forEach(function (_, i) {..})
Where _ indicates the first parameter is not to be used.
The use of underscores like this can get very confusing when using the popular lodash or underscore libraries.
_ in fat arrow function is called as throwaway variable. It means that actually we're creating an variable but simply ignoring it.
More devs are now a days using this as syntactic sugar or short hand while writing code, as it's easy and one character less to write the code.
Instead of using _, you can use other variables like temp, x, etc
for examples:
() => console.log('Hello World')
_ => console.log('Hello World')
x => console.log('Hello World')
But personally i prefer to use () type over throwaway variable if no arguments are needed.
See the following code, then you will understand it better.
_ as an argument,
f = _=> {
return _ + 2 ;
}
f(3) will return 5
For better understanding, check wes bos

passing single argument into a function that requires multiple arguments in javascript

I'm trying to read through some source code on the internet, and I'm getting confused because the author defined a function as:
var _0x80a1 = function (x, a) {...}
But then only calls it using statements like this:
_0x80a1("0x0")
How does that work?
JavaScript parameters are optional you don't need to pass them. So you can do something like this:
function multiply(a, b) {
if(typeof b === 'undefined') {
b = 10;
}
return a * b;
}
console.log(multiply(5));
// expected output: 50
In newer versions of JS you can also do default parameters like this:
function multiply(a, b = 10) {
return a * b;
}
console.log(multiply(5));
// expected output: 50
No function "requires" an argument in JavaScript. It's not a strongly typed language.
I might be typing out of my own butt, but I think function's arguments are syntactic sugar in JS. You can always pass any amount of arguments, regardless of the function's "signature", because the only thing that identifies a function in JS, is its name (and the object on which it is called). That is why, the arguments object exists.
So, as others pointed it out, the second, third, or any other argument that wasn't given will simply be undefined.
An answer on this subject with examples
In ,JavaScript function parameters are optional.If your'e not making use of 'a' inside your function then JS compiler don't care about that.If your'e making use of 'a' inside your function then you will encounter some error like "a is undefined".
function (x,a=10){
}
You can set default parameters like this.Now even if your'r passing one parameter to your function it will run without any errors
I was curious so tried to understand this a bit so I could try to answer.
The variable _8x80a1 is a literal bit definition (https://www.hexadecimaldictionary.com/hexadecimal/0x80A1/) representing e.g. 32929 in decimal.
I'm guessing JS internally numbers all functions when its run. This leaves an entire integer (32766) 'vanilla' functions that can be compiled before using a literal as a function name might cause a conflict.
So the 'x' in the function def. looks like it's passing a string, but it might be just calling 'Function #0' in the _8x80a1 var/function. This would make sense if the function contains multiplpe 'sub functions', as then the 'a' variable can be an object collection (e.g. parameters), that can be passed to the sub-function.
Roughtly, I think .. Not used JS for a whilst and just thought I'd try to help answer! ;-) Essentially a compact way to make a toolkit you can copy between projects, and know your references will all work as expected to your tools, without disrupting e.g. jQuery or other scripts. (Wouldn't be surprised if this is how JS is minified actually ;)).
Chris

What purpose does makeEmptyFunction serve in fbjs?

I was looking through the React source and stumbled across a requirement with var emptyFunction = require('fbjs/lib/emptyFunction');.
I looked at this function and was confused by what it does.
Here is the function
function makeEmptyFunction<T>(arg: T): (...args: Array<any>) => T {
return function() {
return arg;
};
}
const emptyFunction: (...args: Array<any>) => void = function() {};
In the comments, they give the following explanation which I was confused by:
This function accepts and discards inputs; it has no side effects.
This is primarily useful idiomatically for overridable function
endpoints which always need to be callable, since JS lacks a null-call
idiom ala Cocoa
I have never come across null call idiom and was hoping someone could clarify what this means and explain the purpose of this function in less technical language.
Hopefully this question will not get looked down on because it isn't exactly code related. Maybe it belongs somewhere else, if so I'm sorry.
When programming in JavaScript, we can take a function as a parameter to a certain operation. As an example, a function may have a callback which is invoked after some kind of event.
function doIt(callback) {
// some work
callback();
// more work
}
Now if this callback is an optional parameter and it's not provided, we will get Uncaught TypeError: callback is not a function error because callback is undefined. There are two solutions to this issue. The obvious one is checking the callback with an if statement. Another option is set an empty function as the default value of callback if it's not assigned. This approach is very useful and shines if we have multiple places which invoke the callback function. So we don't need to check it for undefined every time before calling it.
function doIt(callback) {
callback = callback || function(){};
// some work
callback();
// more work
}
Likewise, there are lots of use cases where we can have overridable functions variables. It's a common pattern to set these type of variables to empty function as the default value so that we can call them without worrying about whether those are assigned/overridden or not.
Also, in some special cases, it's useful to have functions which do nothing but return a particular value. makeEmptyFunction is used for creating such functions. Basically, it returns a function which does nothing but returns what ever the parameter pass to it.
emptyFunction.thatReturnsFalse = makeEmptyFunction(false);
As you can see in the file, above code generate an empty function which returns false value.
"null call idiom" is something we find in Objective-C/Cocoa programming. It basically allows you to call a method of an uninitialized object (null pointer) without giving any errors like in most of the other languages. I think that's what the author have tried to explain in the comment.
Since JavaScript doesn't have such language feature, we explicitly achieve it using empty functions. Some people call it no-op or noop and you can find similar helpers in other popular JavaScript libraries such as JQuery and AngularJS also.

Empty parentheses vs underscore for ES6 no-args arrow functions [duplicate]

I came across this construct in an Angular example and I wonder why this is chosen:
_ => console.log('Not using any parameters');
I understand that the variable _ means don't care/not used but since it is the only variable is there any reason to prefer the use of _ over:
() => console.log('Not using any parameters');
Surely this can't be about one character less to type. The () syntax conveys the intent better in my opinion and is also more type specific because otherwise I think the first example should have looked like this:
(_: any) => console.log('Not using any parameters');
In case it matters, this was the context where it was used:
submit(query: string): void {
this.router.navigate(['search'], { queryParams: { query: query } })
.then(_ => this.search());
}
The reason why this style can be used (and possibly why it was used here) is that _ is one character shorter than ().
Optional parentheses fall into the same style issue as optional curly brackets. This is a matter of taste and code style for the most part, but verbosity is favoured here because of consistency.
While arrow functions allow a single parameter without parentheses, it is inconsistent with zero, single destructured, single rest and multiple parameters:
let zeroParamFn = () => { ... };
let oneParamFn = param1 => { ... };
let oneParamDestructuredArrFn = ([param1]) => { ... };
let oneParamDestructuredObjFn = ({ param1 }) => { ... };
let twoParamsFn = (param1, param2) => { ... };
let restParamsFn = (...params) => { ... };
Although is declared but never used error was fixed in TypeScript 2.0 for underscored parameters, _ can also trigger unused variable/parameter warning from a linter or IDE. This is a considerable argument against doing this.
_ can be conventionally used for ignored parameters (as the other answer already explained). While this may be considered acceptable, this habit may result in a conflict with _ Underscore/Lodash namespace, also looks confusing when there are multiple ignored parameters. For this reason it is beneficial to have properly named underscored parameters (supported in TS 2.0), also saves time on figuring out function signature and why the parameters are marked as ignored (this defies the purpose of _ parameter as a shortcut):
let fn = (param1, _unusedParam2, param3) => { ... };
For the reasons listed above, I would personally consider _ => { ... } code style a bad tone that should be avoided.
The () syntax conveys the intent better imho and is also more type specific
Not exactly. () says that the function does not expect any arguments, it doesn't declare any parameters. The function's .length is 0.
If you use _, it explicitly states that the function will be passed one argument, but that you don't care about it. The function's .length will be 1, which might matter in some frameworks.
So from a type perspective, it might be more accurate thing to do (especially when you don't type it with any but, say, _: Event). And as you said, it's one character less to type which is also easier to reach on some keyboards.
I guess _ => is just used over () => because _ is common in other languages where it is not allowed to just omit parameters like in JS.
_ is popular in Go and it's also used in Dart to indicate a parameter is ignored and probably others I don't know about.
It is possisble to distinguish between the two usages, and some frameworks use this to represent different types of callbacks. For example I think nodes express framework uses this to distinguish between types of middleware, for example error handlers use three arguments, while routing uses two.
Such differentiation can look like the example below:
const f1 = () => { } // A function taking no arguments
const f2 = _ => { } // A function with one argument that doesn't use it
function h(ff) {
if (ff.length === 0) {
console.log("No argument function - calling directly");
ff();
} else if (ff.length === 1) {
console.log("Single argument function - calling with 1");
ff(1);
}
}
h(f1);
h(f2);
This is based off Bergi's answer, but I thought adding an example was a little more editing than I was happy to do to someone elses post.

Chaining 'bind' and 'call' in JavaScript?

When I reading this answer, find var g = f.call.bind(f);. I can't understand this with my first sight.
So does it has some direct meaning, and has some appropriate usage scenarios?
And further when you using call(or apply) or bind or both in chaining, what will happen? Is there some laws?
var g = f.call.bind(f);. I can't understand this with my first sight.
I assume you're familar with both the .call() and .bind() Function methods? Well, it binds the f.call method to the function f.
Notice that f.call is just Function.prototype.call, it doesn't matter that we access it as a property on f because we don't call it here.
So does it has some direct meaning?
It might become more obvious when we look at the ES6 equivalent:
(Function.prototype.call).bind(f) // or
(f.call).bind(f) // is basically
(...args) => f.call(...args) // or more clear
(ctx, ...args) => f.call(ctx, ...args)
Does it have some appropriate usage scenarios?
Well, now that you know what it does, yes. It can take a prototype method and transforms it to a static function that takes the instance as the first argument. An example:
function Example(n) { this.name = n; }
Example.prototype.display = function() { console.log(this.name); }
Example.display = Function.call.bind(Example.prototype.display);
var e = new Example;
e.display(); // is the same as
Example.display(e);
Are there any laws for further chaining call/apply/bind?
Yes: as always, only the last property in the chain is actually called as a method. In the above example, theres no difference between f.call.bind(…), Function.prototype.call.bind(…) or Function.call.apply.bind.call.bind(…) - it always calls bind on call.
However, by passing them as arguments to each other, you can do some crazy things which are more or less useful.
Good question. Let's start off by considering an example that's come up on StackOverflow before: mapping all the strings in an array to lowercase. Of course I can write
strings . map(function(string) { return string.toLowerCase(); })
but that seems a bit verbose. I'd rather write
strings . map(CALL_LOWERCASE_WITH_ELT_AS_THIS)
So I might try
strings . map(String.prototype.toLowerCase)
or, to use the shorter idiom some prefer
strings . map(''.toLowerCase)
because ''.toLowerCase is exactly equal to String.prototype.toLowerCase.
But this won't work, of course, because map passes each element to the specified function as its first argument, not as its this. Therefore, we need somehow to specify a function whose first argument is used to call some other function as its this. That, of course, is exactly what Function.call does:
function.call(context)
The first argument to call ("context") is used as the this when calling function.
So, problem solved? We ought to be able to just say:
strings . map(''.toLowerCase.call)
and people have tried this and then wonder why it didn't work. The reason is that even though we are passing call of toLowerCase as the callback to map, map still has no idea that the callback is supposed to be called with a this of ''.toLowerCase. We need to explicitly tell map which this to use to call the function, which in the case of map we can do with its second "context" argument:
strings . map(''.toLowerCase.call, ''.toLowerCase)
Actually, since call is the same on any function object, we can simplify this to just
strings . map(Function.call, ''.toLowerCase)
This works and gets the job done beautifully.
However, whereas map provides this second "context" argument to specify the this to call the callback with, that is not something we can depend on being available in all situations. We need a more general way to say "make a function which calls Function.call with some particular function as this".
That is exactly what bind does. It says "take a function and make another function which calls it with a particular this":
function.bind(context)
In our case, what we want to do is to "take the function Function.call and make another function which calls it with a this of ''.toLowerCase. That is simply
Function.call.bind(''.toLowerCase)
Now we can pass this to map without having to use the second argument:
strings . map(Function.call.bind(''.toLowerCase))
That works exactly the same as strings . map(Function.call, ''.toLowerCase), because in general map(fn, ctxt) is precisely equal to map(fn.bind(ctxt)).
The following breaks this down into a readable form, step by step:
Function . // From the Function object
call . // take the `call` method
bind( // and make a new function which calls it with a 'this' of
''.toLowerCase // `toLowerCase`
)
When this construct is specified as a callback, such as to map, it means:
Invoke call with the first argument passed in and ''.toLowerCase as this, which by virtue of the definition of call, means to call toLowerCase with that argument as this.
Some people prefer to simplify this a bit by saying
var call = Function.call;
var toLowerCase = ''.toLowerCase;
strings . map(call.bind(toLowerCase))
or, using the second argument provided by map, just
strings . map(call, toLowerCase)
which is almost readable as English: "map each string to the result of calling toLowerCase.
Another common, related use case would be specifying the callback in a then on a promise. Consider the following code:
promise . then(function(result) { result.frombulate(); })
That's fine, but it's a bit verbose. And then has no way to pass in a context to be used as this when invoking the success or failure handler. But with the above, we can now write:
promise . then(call.bind(frombulate))
There are other use cases for the call.bind idiom, but this is one of the most common ones: define a callback whose effect is to invoke some function with the parameter passed to the callback as its this.
With ES6 fat arrow functions, of course, I can write
promise . then(result => result.frombulate())
so there is relatively less advantage in the shorthand offered by call.bind(frombulate), and it is hard to deny that the fat-arrow version is more readable than that using bind.
The following question might be of interest too: Array.map and lifted functions in Javascript.
m.call.bind(m)
can be used as shorthand for:
function(x){return m.bind(x)()}
The former is the "point-free" form of the latter,
arguments are implicit. It would be useful with
list-operations like map(), making them shorter.
You can write stuff like:
let m = "".toUpperCase;
let fun = m.call.bind(m);
let see = ['a','b'].map(fun);

Categories

Resources