Ask coding questions

← Back to all posts
Lambda challenge question
sammyebinne (0)

Guys I got this question in the Lambda Challenge and it isn't making any sense to me why my answer isn't working.

Modify the function to return true if the array contains a 0, and returns false otherwise.

function doesArrayContainZero(numbers) {

}

/ Do not modify code below this line /

console.log(doesArrayContainZero([1, 2, 3]), '<-- should be false');
console.log(doesArrayContainZero([1, 0, 2]), '<-- should be true');

my answer:

for (var i = 0; i < numbers.length; i++){
if (numbers[i]===0){
return 'true';
} else {
return 'false';
};
};

Answered by mwilki7 (204) [earned 5 cycles]
View Answer
Commentshotnewtop
mwilki7 (204)

return the string “true” or the boolean value true?

if it’s the boolean value then just remove the quotes in the return statement

sammyebinne (0)

@mwilki7
Done that, still doesn't work. I must be getting it wrong somewhere.
https://TestingUnit2.sammyebinne.repl.run

mwilki7 (204)

@sammyebinne
You use both if and else with a return statement.
This means the for loop will only run once before returning a value.

function doesArrayContainZero (numbers) 
{
    for (var i = 0; i < numbers.length; i++)
    {
        if (numbers[i] === 0)
        {
            return true;
        } 
        else 
        {
            return false;
        }
    }
}

console.log(doesArrayContainZero([1, 2, 3]), "<-- should be false");
console.log(doesArrayContainZero([1, 0, 2]), "<-- should be true");

you may want to get rid of the else statement and only return true in the for loop if a zero is found, then return false outside the loop

sammyebinne (0)

@mwilki7
Thanks a lot! This worked. I need to understand why the for...else loop runs only once. More studying needed.

function doesArrayContainZero (arr) {
for (var i = 0; i < arr.length; i++){
if (arr[i] === 0){
return true;
}
};
return false;
}

console.log(doesArrayContainZero([1, 2, 3]), '<-- should be false');
console.log(doesArrayContainZero([1, 0, 2]), '<-- should be true');

ash15khng (305)

You should be returning the boolean value, not the string.
To do so, remove the quotes from the words true and false.
Also, what is a lambda challenge?

sammyebinne (0)

@ash15khng It still didn't work. LAMBDA challenge is a requirement for acceptance into LAMBDA's full stack developer training program. You get timed questions like this.

ash15khng (305)

@sammyebinne Oh, I see. Thanks! Also sorry I couldn't help.