Must use JavaScript Array Functions – Part 1

In this article, we are going to discuss the following two JavaScript array functions

  1.  Array.prototype.every()
  2.  Array.prototype.some()

Both of these functions are widely used in industry and makes the Javascript code clean, modularized and easy to understand.

Array.prototype.every()

Description: Array.every() function is used when you need to validate each element of a given array. Array.every() accepts a callback function as argument which is called for each element of the array. The callback function has to return either a true or false. If all elements of the array satisfy the validation function and thus callback function returns true on all elements of the array, then Array.every() return true. Otherwise Array.every() returns false,as soon as it encounters the first element which does not satisfy the validator function.

Syntax : arr.every(callback[,thisArg])

Parameters :callback : Function to be called for each element of the array arr
currentValue: The value of the elements being processed currently
index(optional): Index of the currentValue element in the array starting from 0
array(optional): The complete array on which Array.every is called

thisArg (optional): Context to be passed as this to be used while executing the callback function.   If context is passed, it will be used as this for each invocation of callback function, otherwise undefined is used as default.

Sample Use Case:
1.To check if every element of the integer array is less than 100
2. To check if every element of the array is of a specific data type, for example String.

Examples

  1. Given an array, write a function to check if all elements of that array are less than 100 or not.

So the naïve approach is to use for loop as shown below.

filter_none

edit
close

play_arrow

link
brightness_4
code

function fnIsLEssThan100_loop(arr){
  for(var i = 0 ; i < arr.length; i ++){
      if(arr[i] >= 100){
          return false;
      }
  }
  return true;
}
function fnIsLEssThan100_loop([30,60,90]);
function fnIsLEssThan100_loop([30,60,90,120]);

chevron_right


true
false

Although the above implementation is easy to understand for any novice programmer but there are some un-necessary checks which the programmer has to take care about. For Example, the short circuiting mechanism i.e. the programmer has to explicitly make sure that as soon as the loop encounters the first element which fails the given condition, the loop should break and return false. Also until and unless the programmer dives deep into the logic of the code, he/she won’t be able to understand what this for loop is doing. But with the use of Array.every(), same behavior can be achieved with much clearer, intuitive and less code.

filter_none

edit
close

play_arrow

link
brightness_4
code

function fnIsLesThan100_Every(arr){
   return arr.every(function(element){
            return(element < 100):
           });
}
  
fnIsLesThan100_Every([30,60,90])
fnIsLesThan100_Every([30,60,90,120])

chevron_right


true
false
  1. Given an array, write a function to check if all elements of that array are of a specified data type.

Again naïve approach would be to iterate over the array using for loop.

 

filter_none

edit
close

play_arrow

link
brightness_4
code

function fnCheckDatatype_loop(arr. sDatatype){
    for(var i = 0 ; i < arr.length; i ++){
      if(typeof(arr[i]) !== sDatatype){
          return false;
}
  
 fnCheckDatatype_loop(["Geeks","for","Geeks"],"string")
 fnCheckDatatype_loop(["Geeks",4,"Geeks"],"string")

chevron_right


true
false

The above code snippet has the same loopholes as the previous example. Using arr.Every() those loopholes are taken care of again in code snippet below. Another point to note in the code snippet below is that we are passing two arguments to the array.every() function. The first one is the callback function (anonymous function in our case) and the second one is sDatatype. Because we need an external variable in each call of callback function, we pass it as a second argument as ‘this’ variable.

filter_none

edit
close

play_arrow

link
brightness_4
code

function fnCheckDatatype_Every(arr, sDatatype){
   return arr.every(function(element){
            return typeof(element) === sDatatype;
           },sDatatype);
}
  
fnCheckDatatype_loop(["Geeks","for","Geeks"],"string")
 fnCheckDatatype_loop(["Geeks",4,"Geeks"],"string")

chevron_right


true
false

Array.prototype.some()

Description:The JavaScript array function Array.some() is in a way opposite of Array.every(). The Array.some()  function is used when you need to check if at least one element of a given array passes the test implemented by the callback function. Array.some() accepts a callback function as argument which has to return either a true or false. The callback function is called for each element of the array until it returns true for at least one element of the array. If neither of the elements in the array pass the test of callback function, Array.some() returns false.

Syntax : Array.some(callback[,thisArg])

Parameters :callback : Function to be called for each element of the array arr
currentValue : The value of the elements being processed currently
index (optional) : Index of the currentValue element in the array starting from 0
array (optional) : The complete array on which Array.some()is called

thisArg (optional):Context to be passed as this to be used while executing the callback function.   If context is passed, it will be used as this for each invocation of callback function, otherwise undefined is used as default.

Sample Use Case:
1.To check if any element of the array greater than 100.
2. To check if any element of the array is even.

Examples

  1. Given an array, write a function to check if array contains any number greater than 100.

Naïve Approach

filter_none

edit
close

play_arrow

link
brightness_4
code

function fnIsGreaterThan100_loop(arr){
    for(var i = 0 ; i < arr.length; i ++){
      if(arr[i] > 100){
          return true;
      }
   }
   return false;
}
  
fnIsGreaterThan100_loop([30,60,90,120]);
fnIsGreaterThan100_loop([30,60,90]);

chevron_right


true
false

Using Array.some()

filter_none

edit
close

play_arrow

link
brightness_4
code

function fnIsGreaterThan100_some(arr){
     return arr.some(function(element){
            return(element . 100):
     });
}
  
fnIsGreaterThan100_some([30,60,90,120]);
fnIsGreaterThan100_some([30,60,90]);

chevron_right


 true
 false
  1. Given an array, write a function to check if array contains any even number.

Naïve approach

filter_none

edit
close

play_arrow

link
brightness_4
code

function fnIsEven_loop(arr){
    for(var i = 0 ; i < arr.length; i ++){
      if(arr[i] % 2 === 0){
          return true;
      }
    }
    return false;
}
  
fnIsEven_loop([1,3,5]);
fnIsEven_loop([1,3,5,6]);

chevron_right


 false
 true

Using Array.some()

filter_none

edit
close

play_arrow

link
brightness_4
code

function fnIsEven_some(arr){
       return arr.some(function(element){
            return(element %2 === 0):
       });
}
  
fnIsEven_some([1,3,5]);
fnIsEven_some([1,3,5,6]);

chevron_right


 false
 true

One of the common mistake programmers do while using array functions like Array.every() and Array.some() is that they forget the return the value in the callback function. Mind it, if you don’t return any value from the callback function, null is returned which will be interpreted as false.

Also, it is important to know that these array functions were introduced in ECMAScript 5. So these functions are supported in IE9 or higher. If you need to use it for older browsers as well, then a library like underscore.js can come to your rescue which has an equivalent implementation of such functions.

Must use JavaScript Array Functions -Part 2

Must use JavaScript Array Functions -Part 3

Additionally, if you wish to dive deeper into the above functions, you can refer to following official links
1. http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.16
2. http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.17

About the author:

“Harshit is a technology enthusiast and has keen interest in programming. He holds aharshit-jain B.Tech. degree in Computer Science from JIIT, Noida and currently works as Front-end Developer at SAP. He is also a state level table tennis player. Apart from this he likes to unwind by watching movies and English sitcoms. He is based out of Delhi and you can reach out to him at https://in.linkedin.com/pub/harshit-jain/2a/129/bb5

If you also wish to showcase your blog here,please see GBlog for guest blog writing on GeeksforGeeks.



My Personal Notes arrow_drop_up

Improved By : ManasChhabra2