Hey guys, what am I doing wrong here? I feel like it’s something with my function syntax but I am not sure, any help is appreciated, thanks
**Your code so far**
function findElement(arr, func) {
let num = 0;
function func() {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === func(num)) {
return arr[i]
}
else {
return undefined;
}
}
}
}
findElement([1, 2, 3, 4], num => num % 2 === 0);
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36
The first thing that stands out here is your findElement array takes a func argument which is the callback function - but then right below it, you redeclare the func as a new function.
function findElement(arr, func) {
let num = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i] === func(num)) {
return arr[i]
}
else {
return undefined;
}
}
}
findElement([1, 2, 3, 4], num => num % 2 === 0);
yes,
I have tried to invoke the parameter func, since its a function and the “true test”,
and if that specific array element passes the test, that return what I need. so
thats why arr[i] === func(num) ( i wasn’t sure how to do it )
This is just a request, but if you’re going to share your code, please format it first. If you right click on the code editor there’s a dialog box that pops up and you can click “Format Document” to format it automatically.
Your code from the original post (the brackets are just totally random, there’s a decreasing indentation, it’s a mess…):
function findElement(arr, func) {
let num = 0;
function func() {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === func(num)) {
return arr[i]
}
else {
return undefined;
}
}
}
}
That same code after clicking “Format Document” ( you can actually see where the blocks of code start and end as their indentations line up):
function findElement(arr, func) {
let num = 0;
function func() {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === func(num)) {
return arr[i]
}
else {
return undefined;
}
}
}
}