0

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

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

the return; is as redundant as in the original question :p

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.