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

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.

Related

I have read many resources and tried to find answer to my question but couldn't. I'm asking about how chaining the higher order functions work

So, this is simple arrow function, but I don't understand how if sth, sth1, etc, works or what are they? Are they arguments as function or just value? or can be both of them? if does, how this chaining works, pls help me out.
const someFunction = sth => sth1 => sth2 => {
// do something if needed
}
What you have there isn't really chained arrow functions (or currying), but a very confusing way of assigning the same function to multiple identifiers at once.
= evaluates from right-to-left, and the whole expression evaluates to the value on the right-hand side. The rightmost side of the assignment is the arrow function expression:
sth2 => {
// do something if needed
}
There, sth2 is an argument.
The arrow function gets assigned to an identifier named sth1:
sth1 = sth2 => { ...
sth1 hasn't been declared yet. This will either throw an error if you're in strict mode, or it'll put a property on the global object with a value of the arrow function in sloppy mode.
Then, that whole section evaluates to that arrow function, and the process repeats itself for sth.
sth = theArrowFunction
Finally, that assignment evaluates to the arrow function, and the identifier someFunction is created that contains the arrow function.
A less confusing way of accomplishing the same thing (in either strict or sloppy mode) is
sth1 = sth2 => {
// do something if needed
};
sth = sth1;
const someFunction = sth1;
But are you sure that's the exact code you're using? If your code was actually
const someFunction = sth => sth1 => sth2 => {
// do something if needed
}
then that's not chained assignment, but currying, where sth, sth1, and sth2 are all arguments for different functions.
This is equivalent to:
const myFun = x => {...}
const sth1 = myFun
const sth = sth1
const someFunction = sth

JavaScript arrow function assignment

I tried googling that , but i can not discuss to google, sometimes in the courses i saw the instructor assign an arrow function to a variable like that.
const s = ( ) => { }
what are the cases when I need that syntax and not using
function s( ) { }
My BASIC Question --> when to use
const s = ( ) => { }
versus
function s( ) => { }
.. why the assignment ... thats my main Question (when and why i assign ?) why not use the arrow function without assigning it to a variable ??
Your examples are showing 2 ways to declare a function.
This is an example of a function declaration.
function s() {
// some code
}
This is another way to define a function, called function expression.
const s = function() {
// some code
}
This is an arrow function. With the exception of the way this is treated between the arrow function and the other two, they are pretty much 3 ways to write the same function.
const s = () => {
// some code
}
As stated in the response below, function declaration and function expression are ES5 features and the arrow function is an ES6 feature.
Your examples do different things: the first declares a function s, the second one calls s().
For the sake of clarity...
// ES5
var multiplyES5 = function(x, y) {
return x * y;
};
// ES6
const multiplyES6 = (x, y) => {
return x * y;
};
Where Arrow Functions Improve Your Code ( where you should use them ) -
One of the primary use cases for traditional lambda functions, and now for arrow functions in JavaScript, is for functions that get applied over and over again to items in a list.
For example, if you have an array of values that you want to transform using a map, an arrow function is ideal:
const words = ['hello', 'WORLD', 'Whatever'];
const downcasedWords = words.map(word => word.toLowerCase());
An extremely common example of this is to pull out a particular value of an object:
const names = objects.map(object => object.name);
Similarly, when replacing old-style for loops with modern iterator-style loops using forEach, the fact that arrow functions keep this from the parent makes them extremely intuitive.
this.examples.forEach(example => {
this.runExample(example);
});
Promises and Promise Chains - Another place arrow functions make for cleaner and more intuitive code is in managing asynchronous code.
Promises make it far easier to manage async code (and even if you're excited to use async/await, you should still understand promises which is what async/await is built on top of!)
However, while using promises still requires defining functions that run after your asynchronous code or call completes.
This is an ideal location for an arrow function, especially if your resulting function is stateful, referencing something in your object. Example:
this.doSomethingAsync().then((result) => {
this.storeResult(result);
});
Object Transformations -
Another common and extremely powerful use for arrow functions is to encapsulate object transformations.
For example, in Vue.js there is a common pattern for including pieces of a Vuex store directly into a Vue component using mapState.
This involves defining a set of "mappers" that will transform from the original complete state object to pull out exactly what is necessary for the component in question.
These sorts of simple transformations are an ideal and beautiful place to utilize arrow functions. Example:
export default {
computed: {
...mapState({
results: state => state.results,
users: state => state.users,
});
}
}
Where You Should Not Use Arrow Functions -
There are a number of situations in which arrow functions are not a good idea. Places where they will not only help, but cause you trouble.
The first is in methods on an object. This is an example where function context and this are exactly what you want.
There was a trend for a little while to use a combination of the Class Properties syntax and arrow functions as a way to create "auto-binding" methods, e.g. methods that could be used by event handlers but that stayed bound to the class.
This looked something like:
class Counter {
counter = 0;
handleClick = () => {
this.counter++;
}
}
In this way, even if handleClick were called with by an event handler rather than in the context of an instance of Counter, it would still have access to the instance's data.
The downsides of this approach are multiple,
While using this approach does give you an ergonomic-looking shortcut to having a bound function, that function behaves in a number of ways that are not intuitive, inhibiting testing and creating problems if you attempt to subclass/use this object as a prototype.
Instead, use a regular function and if necessary bind it the instance in the constructor:
class Counter {
counter = 0;
handleClick() {
this.counter++;
}
constructor() {
this.handleClick = this.handleClick.bind(this);
}
}
Deep Callchains -
Another place where arrow functions can get you in trouble is when they are going to be used in many different combinations, particularly in deep chains of function calls.
The core reason is the same as with anonymous functions - they give really bad stacktraces.
This isn't too bad if your function only goes one level down, say inside of an iterator, but if you're defining all of your functions as arrow functions and calling back and forth between them, you'll be pretty stuck when you hit a bug and just get error messages like:
{anonymous}()
{anonymous}()
{anonymous}()
{anonymous}()
{anonymous}()
Functions With Dynamic Context -
The last situation where arrow functions can get you in trouble is in places where this is bound dynamically.
If you use arrow functions in these locations, that dynamic binding will not work, and you (or someone else working with your code later) may get very confused as to why things aren't working as expected.
Some key examples of this:
Event handlers are called with this set to the event's currentTarget attribute.
If you're still using jQuery, most jQuery methods set this to the dom element that has been selected.
If you're using Vue.js, methods and computed functions typically set this to be the Vue component.
Certainly you can use arrow functions deliberately to override this behavior, but especially in the cases of jQuery and Vue this will often interfere with normal functioning and leave you baffled why code that looks the same as other code nearby is not working.
this excerpt is taken from here
I assume you mean function s( ) { } in your update.
Notice how that function declaration contains the name s. This implicitly creates a variable s and assigns the function to it. An arrow function definition does not contain a name. So in other to use/call/reference the function elsewhere you have to assign it to a variable explicitly.
why not use the arrow function without assigning it to a variable ??
The only why do this is to put calling parenthesis after the definition, e.g.
(() => console.log('test'))()
This will define and call the function immediately, printing "test" to the console.
But there is not much point in doing that, since the code is equivalent to just writing
console.log('test')
So in JavaScript we write function expressions all the time, so much so that it was decided that there should be a more compact syntax for defining them. It's another way to write a function.
const square = x => {
return x * x;
}
I deliberately have no parens surrounding the x because when there is only one argument, current syntax says we can do away with parens.
The above is actually fully functional, you can run square(4); on it and get 16.
Imagine you have nested callbacks written like this:
const square = function(x){
return x * x;
}
Seeing the keyword function all over the place, could drive you batty after awhile.
Arrow functions are cleaner and leaner, but arrow functions is not just syntactic sugar, there is another difference and that is regarding the keyword, this.
If you do not have extensive knowledge of the keyword this, I highly recommend you start to source some solid information out there on the topic, at least as it relates to arrow functions. That research should uncover in what cases you would need to use an arrow function.
As far as why assign it a variable, you have to look at the evolution of the arrow function as outlined by mph85. You go from function declaration:
function isEven(num) {
return num % 2 === 0;
}
to an anonymous function declaration assigned as a variable named isEven:
const isEven = function(num) {
return num % 2 === 0;
}
to the anonymous function declaration assigned to a variable called isEven evolving to an arrow function expression assigned to said variable.
const isEven = (num) => {
return num % 2 === 0;
}
And we can up the ante and make this more concise with an implicit return where we can drop the parens, curly braces and return keyword like so:
const isEven = num => num % 2 === 0;
I think it's important to observe how this evolves so whenever you see the last version above, it will not throw you off.

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

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.

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);

What is the difference between these 2 JavaScript declarations?

For one of them the "()" is inside, for the other one it is outside. Here they are:
var a = (function() {
return {
bla: function() {
console.log('a');
}
};
} () );
var b = (function() {
return {
bla: function() {
console.log('b');
}
};
}) ();
a.bla();
b.bla();
There is no difference.
The [unnecessary] parenthesis are just in different places. The function declaration is already an expression due to where it is located. The parenthesis would make a difference, while still resulting in equivalent code, if the declaration was in a statement context (and ironically they would turn it back into an expression context), which it is not.
The common use of parenthesis in a similar scenario is for self-invoking functions. The parenthesis are required in this case because
function x () { alert("hi!") } ()
is parsed as
function x () { alert("hi!") }; ()
when it appears as a statement -- or "top level element of a block" -- where it is parsed as a "FunctionDeclaration". Thus the following form is often used:
(function () { alert("hi!") })()
This works because function ... is no longer a statement, as above, but an expression (parsed as a "FunctionExpression"), and the expression can continue so the Automatic Semicolon Insertion does not occur as in the previous case. Also note that the function name can be omitted.
However, because in the post the function ... appears in an on the right of an = (in an "AssignmentExpression") it is therefore already in an expression context (is parsed as a "FunctionExpression") and thus no additional parenthesis are needed.
All of these are identical, but I prefer the 2nd form (for consistency within my code):
a = function () {} ()
b = (function () {}) ()
c = (function () {} ())
Happy coding.
There is no real difference. Both work in the same way. If you want to pass JSLint, you will need to use the first pattern, where the invocation parentheses are inside the other set of parentheses. If you don't, you will get the following error:
Move the invocation into the parens that contain the function.
Also note that the first set of parentheses are not required. It will work without them, but again will fail JSLint:
Wrap an immediate function invocation in parentheses to assist the
reader in understanding that the expression is the result of a
function, and not the function itself.
A couple of related questions:
JSLint error: "Move the invocation into the parens that contain the function"
Solution for JSLint errors
There is no practical difference, it's just a subtle difference in how you make the Javascript engine think of the function as a value.
Using ( function(){} () ); you are causing the function to be a value because a statement can't start with a parenthesis. Using ( function(){} ) (); you are using the parentheses to first evaluate the function as a value, then call it.
I think is the same difference of this:
var myObj = {bla:'blabla'};
var a = (myObj);
var b = myObj;
...no difference :)
the ending brackets mean that : When a function is to be invoked immediately, the entire invocation expression should be wrapped in parens so that it is clear that the value being produced is the result of the function and not the function itself. (taken from here)
So, if you use {}(), the function is immediately executed and the variable is assigned with the function result.
Then if you use ({})(), if there's a function between (), it is executed and the value is assigned to the variable.
They are the same thing if they contain the same functions in my opinion.

Categories