This question already has answers here:
Arrow function without curly braces
(9 answers)
Closed 6 years ago.
I have seen a code something like while learning React
const LinkCell = ({rowIndex, data, col, ...props}) => (
<Cell {...props}>
{data.getObjectAt(rowIndex)[col]}
</Cell>
);
Also, so far I thought that in ES6 function shorthand is
let sum = (a, b)=>{
return a + b;
}
How the first one is different from the second one ?
() => () is a one liner shorthand of () => { doSomething() OR return; }.
Anyways, if you need more manipulations and need more than one line statement, you should go for () => {} syntax otherwise you can use a shorthand syntax () => ()
The following are also treated as one line statement. But to use with () => () syntax, you need to rewrite it without return statement,
// The below one line statement can be rewritten as below
if (true ) return something;
// rewritten of above one
() => ( a > b ? a : b)
// one line statement
if (true ) invoke(); // This will go like, () => (a ? a.invoke() : b.invoke())
// one line statement
for(var i in results) doSomething();
//And your jsx statement which can be tread as one liner
<Cell {...props}>
{data.getObjectAt(rowIndex)[col]}
</Cell>
with the ()=> () syntax imagine if there was an implicit return statment e.g. () => {return ()}
Related
I was wondering if anyone could clarify the following.
What is the difference between this:
function(arg).then((ret) => {
anotherFunc(ret);
}).catch(error)
and this:
function(arg).then((ret => {
anotherFunc(ret);
})).catch(error)
Difference is the brackets when the promise is returned.
Your second example looks strange. I think your question has to do more with arrow functions syntax. If arrow functions have one argument, you can skip the parentheses. For example .
const logA = a => console.log(a);
const logB = (b) => console.log(b);
As you see, logA argument doesn't have (), logB argument does have (b). They both work exactly the same way, just a syntax preference.
function(arg).then((ret) => {
anotherFunc(ret);
}).catch(error)
OR
function(arg).then(ret => {
anotherFunc(ret);
}).catch(error)
Are the same.
This question already has answers here:
How to return anonymous object from one liner arrow function in javascript? [duplicate]
(3 answers)
Closed 3 years ago.
I am having code from youtube tutorial, and i can not figure out why do we need parentheses(commented line), and if anyone can explain in simple way this code... thanks
const [{count, count2}, setCount] = useState({count: 10, count2: 20})
return (
<div className="App">
<button onClick={ () =>
setCount(
currentState => (//can not understand
{...currentState, count: currentState.count+1}
)
)}>+</button>
<h5>Count 1: {count}</h5>
<h5>Count2: {count2}</h5>
</div>
)
This has nothing to do with the spread operator.
The => of an arrow function can be followed by either:
An expression
A block
Since, in JavaScript, a { can start a block or an object initializer (which depends on context), anywhere you could put a block but want an object initializer you need to add wrap it in () so that the { is treated as the start of an expression.
why do we need parentheses
I guess because without them (), it won't work, throws the error even on compile time.
setCount(
currentState => (//can not understand
{...currentState, count: currentState.count+1}
)
)
setCount is a setState hooks. It has 2 syntax:
setCount( newStateOfCount ) (set state with direct value)
setCount( oldCount => newCount ) (set state using a callback)
And yours is the second one. With the callback return an object, you have 2 options:
currentState => {
return {
...currentState,
count: currentState.count+1
}
}
which is more verbose than
currentState => ({
...currentState,
count: currentState.count+1
})
So in the tutorial he used the second syntax, because it's more concise.
Without the parentheses it doesn't work:
currentState => {
...currentState,
count: currentState.count+1
}
Because the parser will understand that { is the begin of a function body, rather than an object, it won't be able to figure it out, without you explicitly give it the ()
This question already has answers here:
What do multiple arrow functions mean in JavaScript?
(7 answers)
When should I use a return statement in ES6 arrow functions
(6 answers)
Closed 3 years ago.
I'm a newbie
I've download some source in this link
https://github.com/the-road-to-learn-react/react-redux-example
i have some proplem
in file src/app.js line 4
const applyFilter = searchTerm => article =>
article.title.toLowerCase().includes(searchTerm.toLowerCase());
why this can't work with
const applyFilter = searchTerm => article =>{
article.title.toLowerCase().includes(searchTerm.toLowerCase());
}
or
const applyFilter = searchTerm => {article =>
article.title.toLowerCase().includes(searchTerm.toLowerCase());
}
and in line 14 when call the funtion
articles.filter(applyFilter(searchTerm))
const applyFilter = searchTerm => article =>
article.title.toLowerCase().includes(searchTerm.toLowerCase());
this in my mind is call an arrow function inside an arrow function?
How can they put var 'article' in??
Arrow function syntax is kinda like this
(a) => b(a);
is equivalent to
function(a) {
return b(a);
}
However, when you add {} to an arrow function, it changes the meaning:
(a) => { b(a); }
is equivalent to
function(a) {
b(a);
// notice that this doesn't actually return anything,
// it just calls a function and does nothing with the result
}
So you have to add a return statement when you add brackets
(a) => { return b(a); }
This question already has answers here:
When should I use a return statement in ES6 arrow functions
(6 answers)
Closed 1 year ago.
return valuesArray.map((objValue) => {
Dataset.find(dataObj => dataObj.value === objValue)
});
it returns undefined. However, if I use forEach and push values into an new array, it works.
You can also check with filter to check for undefined.
return valuesArray.map((objValue) => {
return Dataset.find(dataObj => dataObj.value === objValue)
}).filter(y => y != undefined);
So it will not return the undefined from the valuesArray also.
You're missing a return value.
With anonymous functions, if you encase the function in curly braces, you have to explicitly return a value.
() => 1: returns 1
() => { 1 }: returns undefined
() => ({}): returns {}
To answer your question, here are 2 methods that will work:
return valuesArray.map((objValue) => {
return Dataset.find(dataObj => dataObj.value === objValue)
});
or
return valuesArray.map((objValue) => Dataset.find(dataObj => dataObj.value === objValue));
Arrow functions can be written in a lot of different ways, are there any way that is "more correct"?
let fun1 = (a) => { return a; }
let fun2 = a => a;
Just like those cases above, is fun2 faster then fun1? What's the diference between them?
Arrow functions can be written in some diferent ways, like below:
// No params, just returns a string
const noParamsOnlyRet = () => 'lul';
// No params, no return
const noParamsNoRet = () => { console.log('lul'); };
// One param, it retuns what recives
const oneParamOnlyRet = a => a;
// Makes the same thing that the one above
const oneParamOnlyRet2 = a => { return a; };
// Makes the same thing that the one above
const oneParamOnlyRet3 = (a) => a;
/* Makes the same thing that the one above, parentheses in return are optional,
* only needed if the return have more then one line, highly recomended put
* objects into parentheses.
*/
const oneParamOnlyRet4 = (a) => (a);
// Mult params, it returns the sum
const multParamsOnlyRet = (a, b) => a + b;
// Makes the same thing that the one above
const multParamsOnlyRet2 = (a, b) => { return a + b; }
// Curly brackets are needed in multiple line arrow functions
const multParamsMultLines = (a, b) => {
let c = a + b;
return c;
}
So we have some rules:
Parentheses around the params are needed when the function has none or more than one param, if it have just one, parentheses can be omitted.
If the function just have a return the curly brackets and the keyword return can be omitted, if it fits in one line
Curly brackets are needed if the function have more than one line or if it have no return.
As you can see, all of this are valid syntax for arrow functions, none of them is faster than the other, which one you use depends of the way that you code.
From
function(a){return a}
remove function and add => between the () and the {}:
(a) => {return a}
If you only have one argument, you can remove the brackets:
a => {return a}
if everything in the {} is a return statement, you can remove the {return ...} and leave just the statement:
a => a