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';
};
};

You are viewing a single comment. View All
mwilki7 (193)

@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