Problems In JavaScript Arrow Function [duplicate] - javascript

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

Related

Why does await is not working in my function? [duplicate]

This question already has answers here:
How to return many Promises and wait for them all before doing other stuff
(6 answers)
Closed 2 years ago.
I am trying to push in an array all the ids of objects that match my condition.
I am using a recursive function and I want to return a value when my recursive function has finished.
Here is my code :
const getFamilies = async function (family, famillesReliees) {
await strapi.query('famille-de-materiel').findOne({ id: family })
.then(res => {
if (res.cats_enfant.length > 0) {
res.cats_enfant.forEach(async enfant => {
famillesReliees = await getFamilies(enfant.id, famillesReliees)
})
} else {
famillesReliees.push(res.id)
}
})
return famillesReliees
}
async search() {
let value = await getFamilies(2, [])
return value
}
I don't understand why the "value" return before the end of the recursive function
This isn't doing what you think:
getFamilies(2).then(console.log('getFamilies then'))
This executes console.log immediately and passes its result (which is undefined) as the function to be executed after the getFamilies operation.
Wrap the console.log operation in a function to be executed later:
getFamilies(2).then(() => console.log('getFamilies then'))
Structurally, this is just like your use of .then() in the getFamilies function above. The only differences are:
There are no parameters/arguments for the function, so just use () instead of a variable name. (Your callback function above has a parameter called res.)
There's only one line in the function, so the curly braces {} aren't needed. (Technically this also returns the result of that line, but in this case the returned result is undefined and nothing uses it so no harm done.)

Spread operator [duplicate]

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

Why do curly braces and/or whitespace make a difference? [duplicate]

This question already has answers here:
When should I use a return statement in ES6 arrow functions
(6 answers)
Closed 4 years ago.
Why is this-
const squareList = (arr) => {
"use strict";
const sqr = arr.filter((numbers) => {
numbers > 0 && Number.isInteger(numbers)
}).map((numbers) => {
Math.pow(numbers, 2)
})
return sqr;
};
functionally different to this-
const squareddList = (arr) => {
"use strict";
const sqr = arr.filter((numbers) => numbers > 0 && Number.isInteger(numbers)).map((numbers) => Math.pow(numbers, 2))
return sqr;
}
when the only difference between them is whitespace and curly braces?
When you pass an arbitrary array to both functions, the first returns an empty array and the second returns an array which has been filtered to only include positive integers and then squared.
Arrow functions without curly braces implicitly return the result of the expression in the function body so:
const someFunction = () => 10
someFunction(); // Returns 10
is equivalent to
const someFunction = () => {
return 10;
}
someFunction(); // Returns 10
and is NOT equivalent to:
const someFunction = () => {
10;
}
someFunction(); // Returns undefined
The difference is because in the first one you don't return the values.
In arrow function, if you put curly brackets you need to return the value, if not the values are returned.
const squareList = (arr) => {
"use strict";
const sqr = arr.filter((numbers) => {
return numbers > 0 && Number.isInteger(numbers)
}).map((numbers) => {
return Math.pow(numbers, 2)
})
return sqr;
};
This will work.

.find within .map() returns undefined - JavaScript ES6 [duplicate]

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

Javascript ES6 Difference between ()=>() and ()=>{} [duplicate]

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 ()}

Categories

Resources