This is something I still don't quite understand very well, I have the following situation:
// #2) Check if this array includes any name that has "John" inside of it. If it does, return that // name or names in an array. const dragons = ['Tim', 'Johnathan', 'Sandy', 'Sarah'];
at first I tried the following:
const name = dragons.forEach(element => {
element.includes("John") ? element : null
});
it returns undefined
then:
const name = dragons.filter(element => {
element.includes("John");
});
it returns an empty array
then:
function name() {
const dragons = ['Tim', 'Johnathan', 'Sandy', 'Sarah'];
dragons.forEach(element => {
if (element.includes("John")) {
return element;
}
});
}
again it returns undefined
but the interesting thing is that if on any of the attempts I change the action to do to console.log(element); then it will show "Johnathan" which is the correct output.
so it means that the logic is working, I just don't understand why it won't return the value if I want to let's say assign it to a variable.
I even tried the following:
const dragons = ['Tim', 'Johnathan', 'Sandy', 'Sarah'];
dragons.forEach(element => {
if (element.includes("John")) {
const name = element;
}
});
but it again returns name as undefined, why is that?
edit: this was my first stack overflow question, really I wasn't expecting someone answering my question, I thought maybe it was a dumb question or that i didn't explained myself well but it was very nice to find such a supportive community, thank you so much to all of you who commented and helped me!
element => { element.includes("John"); }andelement => element.includes("John"). One of the two works, the other doesn't.forEachalways returnsundefined. Even if you return a value in the callback, which you don't. For the second attempt see: When should I use a return statement in ES6 arrow functions. For the third: Function with forEach returns undefined even with return statement. For the fourth: What is the scope of variables in JavaScript?.some()orevery()const name = dragons.filter(element => element.includes("John"));and now it outputs the correct result, so the mistake was to include the curly brackets and the ; after the statement? thank you so much @WiktorZychla for clarifying!["John", "John", "John"]or?... Could you explain your exact task?