Ahmed Hassan
Ahmed Hassan

Reputation: 39

Javascript function not returning false

This function is only returning true. I have added a console.log in the if block and it is called but the function doesn't return false.

function isUniform(List)
{
    var ele = List[0];
    List.forEach(function(item)
    {
        console.log(ele);
        if(ele !== item)
        {
            return false;
        }
    })
    return true;
}

Upvotes: 0

Views: 980

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386520

You need another method for testing unifomity. Better use Array#every, which checks every value with the first item of the array and return true, if all elements are equal and false if not. The iteration stops with the first unequal element.

function isUniform(list) {
    return list.every(function(item, _, array) {
        return item === array[0];
    });
}

The used Array#forEach returns always undefined:

forEach() executes the callback function once for each array element; unlike map() or reduce() it always returns the value undefined and is not chainable.

Upvotes: 9

muratoner
muratoner

Reputation: 2672

I think you can use this code;

function isUniform(List)
{
    var res = true;
    var ele = List[0];
    List.forEach(function(item)
    {
        console.log(ele);
        if(ele !== item)
        {
            res = false;
            return;
        }
    })
    return res;
}

Upvotes: 0

Related Questions