I have done that but as it is required in the second question (findElement([1, 3, 5, 9], function(num) { return num % 2 === 0; })should return undefined.) doesn’t return undefined if not written in quotes. it returns if it is written in quotes.
which one (within quotes or without quotes) is correct?
function findElement(arr, func) {
let num = 0;
forloop
num is assigned
if func num
num is returned
}
return undefined;
}
console.log(findElement([1,3,5,9], num => num % 2 === 0));
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0.
If none of the elements in the array return True for the function provided, Undefined is correct.
“Undefined” (in quotes) is a string, and is incorrect.
Thanks for replies
I was thinking undefined should logged into console that’s why I used “undefined” it does log but doesn’t pass the test.
undefined without quotes passes the test but isn’t logged in to console which is correct.
The confusion was that it is said in MDN undefined property represents the primitive value undefined that’s why I thought it should return/log undefined
console.log(findElement([1, 3, 5, 9], num => num % 2 === 0)); probably did log undefined to the Dev Tools console but not to the FCC environment.
Since you have a solution I can show you this pseudo code.
function findElement(arr,func){
loop through array{
if(func(arr[i])){
return arr[i]; // if pass truth test then return val
}
} // if none pass truth test, do nothing at all
}
By simply not explicitly returning anything you are returning undefined - the function did return but the return value was never set so is undefined.
I believe the way their test checks is with ===, so since you are returning a string and they are looking for a number it fails the test. You can get the first element of the array with [0] in stead.
function findElement(arr, func) {
"use strict"
let [a] = arr.filter(num => func(num));
return a;
;
}
But I learned that it would be more effective if not making the algorithm iterate with the whole array so I guess the below would be even shorter and effective:
function findElement(arr, func) {
"use strict"
return arr.find(func);
}