Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript array.some() function does not work as it should?

I'm doing a web project using AngularJS, but in one of the control checks I'm trying to implement the array.prototype.some()-function. Unfortunately, it does not work, and always gives false.

In my attempts at finding the error, I tried to implement a simple test case where an array with numbers are checked for values higher than 5.

The test code is this:

var arrayForTesting = [2, 5, 18];

var result = arrayForTesting.some(function (element, index, array){
    element > 5;
});

Some webpages implied that I need index and array as mandatory parameters, but only element is the only parameter I require for this test.

However, result still becomes false, but there is at least one element higher than 5.

What am I doing wrong?

like image 261
Darth_Sygnious Avatar asked Dec 01 '22 13:12

Darth_Sygnious


1 Answers

You're not returning the result of the element > 5 comparison; perhaps you've seen ES2015 "arrow functions" and are getting their concise syntax confused with function function syntax (or possibly you've seen some CoffeeScript).

When using function syntax, you must return the result:

var arrayForTesting = [2, 5, 18];
var result = arrayForTesting.some(function (element, index, array){
    return element > 5;
//  ^^^^^^
});

If the function exits without a return xyz statement (or uses return; with no operand), the result of calling the function is undefined, which is falsey, so some doesn't stop looping.

With ES2015, if you use an arrow function and a "concise function body," the return is implicit:

var arrayForTesting = [2, 5, 18];
var result = arrayForTesting.some(element => element > 5);

But only with concise bodies (no {}), otherwise you use return as with function functions:

var arrayForTesting = [2, 5, 18];
var result = arrayForTesting.some(element => {
    return element > 5;
});

Note that while cutting-edge browsers are actively updating their JavaScript engines to add ES2015 features, support on the ground is still sparse enough you probably need to transpile to use ES2015 features like arrow functions. (Not least if you need to support older browsers like IE10.)

like image 118
T.J. Crowder Avatar answered Feb 01 '23 02:02

T.J. Crowder