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!