Difference between ()=> and _=> and (_)=> in JS ES6 [duplicate] - javascript

This question already has answers here:
ESCMAScript 6 arrow functions - parentheses around parameter
(1 answer)
Using _ (underscore) variable with arrow functions in ES6/Typescript
(4 answers)
Closed last year.
I have notice that when I want to write a fat arrow function "=>" I can do _=>, ()=>
or (_)=> and my code functions the same (at least for my use cases)
Is there an actual difference between them? If yes, which one should I use? I have been using ()=> most of the time, but then one day I saw someone's code using _=> and I thought it looked cool, so I started using it too.
I saw this medium article https://medium.freecodecamp.org/when-and-why-you-should-use-es6-arrow-functions-and-when-you-shouldnt-3d851d7f0b26 where the author states you can use _=> or ()=> but doesn't specify if there's a difference.

The general form of a fat-arrow function is
(parameter-list) => function-body
If you don't have any parameters, you use a pair of empty parentheses:
() => {}
If you have a single parameter it's:
(x) => {}
Since _ is a valid identifier in JavaScript, you can do:
(_) => {}
Now, a special rule applies: If you have only one parameter, you can skip the parentheses, so you get:
_ => {}
Please note that this is only valid if you have a single parameter, i.e. for two you always have to specify the parentheses:
(x, y) => {}
Now, on the right side, if your entire function only consists of a single statement with a return, such as
x => { return x; }
you can omit the curly braces and the return:
x => x
At least, this is true if on the right side you don't try to return an object, which would look like this (this code won't work!):
x => { value: x }
The reason why this does not work is that JavaScript can not distinguish this from a function body, which also uses curly braces, so now you have to wrap it in parentheses:
x => ({ value: x })
I think that's pretty much everything you need to know about the syntax of fat arrow functions.

You should not use something just because it looks cool.
_ is often used to tell a linter (or reader) that you do not use an certain argument on purpose.
So if you have a callback with two arguments and you only use the second one you would write (_, arg) => console.log(arg) because if you would write (foo, arg) => console.log(arg) then the linter would complain about foo not being used.
And some APIs might have different behavior depending on the number of arguments the callback has (the middlewares of expressjs are an example for that), so if the API checks the length property of the callback then you might need to use a placeholder like _.
var cb1 = _ => {};
var cb2 = () => {};
console.log(cb1.length)
console.log(cb2.length)

Arrow functions take any number of parameters, just like "regular" functions. When there are no parameters, this is indicated by () => {}, similarly to function() {}. If you have exactly one parameter, though, the parenthesis may be omitted. This leads to a syntax like _ => {} like you've noted — this is identical to (_) => {}, as an underscore is a valid identifier (just like foo).
The runtime difference in your specific situation seems to be none, as you're (presumably) not passing any parameters, in which case _ is undefined. You can easily verify this:
const foo = _ => console.log(_);
foo(5); // logs 5
foo(); // logs undefined
That's not to say you should do it, just that it doesn't make a difference for now. If you added a parameter later, it could wreak havoc.

Related

Arrow function syntax with parentheses instead of curly braces? [duplicate]

This question already has answers here:
Arrow function without curly braces
(9 answers)
Closed 2 years ago.
I saw a code snippet in a React tutorial:
const App = ({title}) => (
<div className="header">{title}</div>
);
At first glance, I thought it assigned an arrow function to the App constant. Then I noticed it doesn't use curly braces but parentheses.
I understand arrow function should be (...) => {...}, but here it uses (...) => (...)
So, is it an arrow function or not? If it is, why there is another form? How can I decide when to use which form? If it isn't, what's this function type called in js?
Yes, it's also an arrow function. The only difference, is that if you don't use braces, it forces a return:
const App = () => { return true; } // with braces you've to use the return statement
const App = () => true; // without braces it forces the return statement automatically
The MDN arrow function expression documentation says the following about this:
Function body
Arrow functions can have either a "concise body" or the usual "block
body".
In a concise body, only an expression is specified, which becomes the
implicit return value. In a block body, you must use an explicit
return statement.
var func = x => x * x;
// concise body syntax, implied "return"
var func = (x, y) => { return x + y; };
// with block body, explicit "return" needed
Furthermore, with regard to the parentheses: the arrow function in this case returns a JSX expression, which is considered a single object.
Parentheses are mostly used for multi-line JSX code. See more information here: https://reactjs.org/docs/introducing-jsx.html
and also the other similar question on Stack overflow.
When you use the syntax:
const a = ({ foo }) => ( <Component /> );
This means that the code inside the brackets is inherently returned. I.e., the fat arrow the return is forced. Whereas this syntax:
const b = ({ bar }) => {
some();
thing();
};
This would indicate actions performed, but nothing is returned. Ie the 'return' keyword must be present for anything to be returned from the function, like this:
const c = ({ baz }) => { return <AnotherComponent />; }
The first and third examples with a return (implicit or otherwise) would be useful for reusable functions and/or components. The middle one where nothing is returned would be more useful for state management (mobx/redux/flux for example) where you'd need to implement HOF or functions that return state or objects.

How to declare a react js declare function?

There are many different ways of declaring a function, some end with semicolon others not. I would like to know what the difference is:
A
addUser = id => {
this.setState(// ...);
};
B
selectTask(option) { this.setState({task: option}); }
This is more related to Javascript then React itself.
First one is a function expression and semicolons are recommended for them since there could be some edge and weird cases we can encounter. Examples:
const foo = function() {
console.log("first");
};
// Do not bother with this function too much, it is here to mimic our error,
// and does not have to be an arrow function.
(() => console.log("second"))();
What we expect is here to see second as output and if you run this we actually see. What if we omit semicolon in the first expression?
const foo = function() {
console.log("first");
}
(() => console.log("second"))();
What happens here is since we omit semicolon our second iife function is taken into account as an argument for our first function and our first function is executed but this is not what we intended here.
But, for function declarations this is different.
function foo() {
console.log("first");
}
(() => console.log("second"))();
Omit the semicolon or do not, the result is the same: We see second as output and this is what we expect. Hence, semicolon is not recommended here.
Now, arrow functions are a little bit different about that. Actually they are function expressions and can have two kinds of body type. A concise one which has one single expression and return is explicit. The other one is a body block and needs a return. Now, bear with me since there are different cases here.
const foo = () => console.log("first");
( () => console.log( "second" ) )();
Here we have concise body, a single expression with a semicolon. Everything is as expected, we see "second". But if we omit semicolon:
const foo = () => console.log("first")
( () => console.log( "second" ) )();
it does nothing since there is an explicit return in our arrow function. Now with a regular body block either with semicolon or not:
const foo = () => { console.log("first") }
( () => console.log( "second" ) )();
it is being treated as a function declaration and our result does not change. Actually I'm not quiet sure about my explanation of "treated as a function declaration", if someone corrects me I will be glad to edit my answer.
Option A: is Called Arrow Function
Arrow functions don’t redefine the value of this within their function body. This makes it a lot easier to predict their behavior when passed as callbacks and prevents bugs caused the by use of this within callbacks. Since it is arrow function or function expression it needs to end with a semi-colon.
Option B: is Normal Function it requires this and bind to be used in callbacks. It is a function declaration statement, hence there is no need of semicolon.
Important: Avoid arrow functions and bind in render in react.
if we are binding in render then we don't need to end with semicolon
Click Me
else
this.handleClick = this.handleClick.bind(this);

Are these functions call equivalent?

Recently I have seen these functions in tutorials. Are they equivalent?
(_ => console.log(1))();
(() => console.log(1))();
The two functions do exactly the same thing. The only difference is that the top function takes one parameter, _, while the other takes zero. This doesn't matter in this example, since you don't use the _ variable.
If however, you are using _ as a variable name, and you use it in the function, you will run into problems. Example:
(_ => console.log(_))();
is not the same thing as
(() => console.log(_))();
In the first line, the function prints the value of the parameter _, which, in this case is undefined, since no value is passed to it. In the second line, the function prints the value of the global variable _. This can become a problem if you use a library like underscore.js, where the variable _ is used.
A "fat arrow" (=>) function can be declared with a single identifier parameter name, or with a parenthesized lists of zero or more parameters. Your first example
(_ => console.log(1))();
is the first case, with the parameter name being "_". The second example is a parameter list with no parameters:
(() => console.log(1))();
Neither function makes use of its parameters, and both invocations pass no parameters. That is, both function calls have no actual arguments; the statements both end with (). Whether the two are "equivalent" or not depends on your definition of "equivalent". In both cases, exactly the same thing will happen. However, the anonymous fat-arrow functions are not exactly the same.
No, they are not equivalent. The first is an anonymous fat arrow function with 1 parameter, the second is an anonymous fat arrow function with 0 parameters. The first, thus, relies on the fact that passing too few arguments to a function is not an error in ECMAScript.
The underscore _ is sometimes used to indicate a parameter that is required to fulfill a certain contract but is actually ignored. However, in this case, that is a misuse of this convention since the parameter isn't required: the function is called without arguments, so there is no need to declare a parameter.

What exactly does the anonymous JavaScript function f => f do?

I'm using a third-party library that has a function that takes functions as arguments. I'm doing some conditional checks to decide whether or not to add a particular function as a parameter and in some cases I don't want to provide a function. Providing null in that cases throws an error.
I found this code which works, but I don't fully understand what's happening.
compose(__DEV__ ? devTools() : f => f)
Is f => f equivalent to () => {} an empty anonymous function?
f => f is the identity function. It simply returns the argument that was passed in.
This function is often used as a default values for transformation processes, since it doesn't perform any transformation.
Is f => f equivalent to () => {} an empty anonymous function?
No. The empty function doesn't return anything. The identity function returns the passed in argument.
f => f is similar* to function(f){ return f; }
So close, but not quite what you expected.
* - as has been pointed out in comments, there are subtle differences, but for the sake of your question, I don't think they are particularly relevant. They are very relevant in other situations.
If you want to know what f => f means, the left side is the parameter and the right side is the return value. So for example, f => f*2, is equivalent to:
function(f) {
return f * 2;
}
The code which you describe returns whatever is supplied to it as input.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions
Others have already mentioned what f => f does, so I'm not going to go deeper into that. I'm just going to explain the rest of the function, because there's a bit of a difference between f => f and __DEV__ ? devTools() : f => f
The ternary operator checks if __DEV__ is a truthy value, and if so, it return function devTools(). otherwise, it return the identity function f => f which does nothing. Put differently: this code enables some development mode functions. Without the remaining code, it's hard to tell what this mode adds, but presumably, it will enable some extra logging information and less obfuscation.
Anytime with the similar dilemma, you can use Babel to get the answer.
It returned like this:
"use strict";
(function (f) {
return f;
});
BTW, => you used is ES6 feature called arrow expression.
The other expression of interest
() => {}; // es6
would convert to:
(function () {});
Since arrow function expressions are always anonymous it makes sense if you add the name to the function:
let empty = () => {}; // es6
would convert to
var empty = function empty() {};

What is the meaning of an Underscore in javascript function parameter?

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

Categories