Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
Most useful JavaScript Array Functions – Part 2
Next article icon

Most useful JavaScript Array Functions – Part 1

Last Updated : 04 Aug, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we are going to discuss the following two JavaScript array functions. Both of these functions are widely used in industry and make the JavaScript code clean, modularized, and easy to understand.

  • Array.prototype.every()
  • Array.prototype.some()

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

Syntax:

arr.every(callback(element[, index[, array]])[, thisArg])

Parameters: This function accepts five parameters as mentioned above and described below:

  • callback: This parameter holds the function to be called for each element of the array.
  • currentValue: The parameter holds the value of the elements being processed currently.
  • index: This parameter is optional, it holds the index of the currentValue element in the array starting from 0.
  • array: This parameter is optional, it holds the complete array on which Array.every is called.
  • thisArg: This parameter is optional, it holds the context to be passed as this is to be used while executing the callback function. If the context is passed, it will be used as this for each invocation of the callback function, otherwise undefined is used as default.

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

Example 1: In this code, we will check the array by using a loop function. So the naive approach is to use for loop as shown below. Although the below implementation is easy to understand for any novice programmer, there are some unnecessary checks which the programmer has to take care of. 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. 

JavaScript
let numbers = [30, 60, 190]; let result = true; for (let i = 0; i < numbers.length; i++) {     if (numbers[i] >= 100) {         result = false;         break;     } } console.log(result); 

Output:

false

Example 2: In this code, we will check the array by using an Array.prototype.every() function. So the naive approach is to use for a loop as shown below. with the use of Array.every(), the same behavior can be achieved with much clearer, more intuitive and less code. 

JavaScript
let numbers = [30, 60, 90]; let result = numbers.every(function (element) {     return (element < 100); });  console.log(result); 

Output:

true

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

Example 1: Again naive approach would be to iterate over the array using for loop. This code snippet has the same loopholes as the previous example. 

JavaScript
function fnCheckDatatype_Every(arr, sDatatype) {     for (let i = 0; i < arr.length; i++) {         if (typeof (arr[i]) != sDatatype) {             return false;         }     }     return true };  console.log(fnCheckDatatype_Every(["Geeks", 4, "Geeks"], "string")); console.log(fnCheckDatatype_Every(["Geeks", "for", "Geeks"], "string")); 

Output:

false
true

Example 2: Using arr.Every() of those loopholes is taken care of again in the 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 a callback function, we pass it as a second argument as ‘this’ variable. 

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

Output:

true
false

Array.prototype.some(): This is in a way opposite to Array.every(). This 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 an 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 passes the test of the callback function, it returns false. 

Syntax:

arr.some(callback(element[, index[, array]])[, thisArg])

Parameters: This function accepts four parameters as mentioned above and described below:

  • callback: This parameter holds the function to be called for each element of the array.
  • currentValue: The parameter holds the value of the elements being processed currently.
  • index: This parameter is optional, it holds the index of the currentValue element in the array starting from 0.
  • array: This parameter is optional, it holds the complete array on which Array.every is called.
  • thisArg This parameter is optional, it holds the context to be passed as this is to be used while executing the callback function. If the context is passed, it will be used as this for each invocation of the callback function, otherwise undefined is used as default.

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

Example 1: Naive Approach 

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

Output:

true
false

Example 2: Using Array.some() 

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

Output:

true
false

Given an array, write a function to check if an array contains an even number.

Example 1: Naive approach 

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

Output:

 false
true

Example 2: Using Array.some() 

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

Output:

 false
true

One of the common mistakes 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 

This article is contributed by Harshit Jain


Next Article
Most useful JavaScript Array Functions – Part 2

H

Harshit Jain
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-array
  • javascript-functions

Similar Reads

  • Most useful JavaScript Array Functions – Part 2
    In Most useful JavaScript Array Functions – Part 1, we discussed two array functions namely Array.Prototype.Every() and Array.prototype.some(). It is important to note that both of these array functions accessed the array elements but did not modify/change the array itself. Today we are going to loo
    7 min read
  • Must use JavaScript Array Functions – Part 3
    Previous articles: Must use JavaScript Array Functions -Part 1 Must use JavaScript Array Functions -Part 2 In this article, we are going to discuss the following JavaScript array functions prototype.reduce()prototype.concat()prototype.sort()prototype.reverse() JavaScript Array.Prototype.reduce(): Ar
    5 min read
  • Array of functions in JavaScript
    Given an array containing functions and the task is to access its element in different ways using JavaScript. Approach: Declare an array of functions.The array of functions works with indexes like an array function. Example 1: In this example, the function call is initiated from the element of the a
    2 min read
  • JavaScript Array join() Function
    The JavaScript Array.join() method is used to join the elements of the array together into a string. The elements of the string will be separated by a specified separator and its default value is a comma(, ). Syntax: Array.join([separator]) Parameters: [separator]: A string to separate each element
    2 min read
  • Dense and Sparse Array in JavaScript
    In JavaScript, an array is a data structure used for storing a collection of values. Each value in the collection is assigned a unique index number. Arrays in JavaScript can contain values of any data type, such as strings, numbers, objects, and even other arrays. In JavaScript, arrays can be of two
    7 min read
  • JavaScript Array find() function
    JavaScript arr.find() function is used to find the first element from the array that satisfies the condition implemented by a function. If more than one element satisfies the condition then the first element satisfying the condition is returned. Syntax: arr.find(function(element, index, array), this
    3 min read
  • Types of Arrays in JavaScript
    A JavaScript array is a collection of multiple values at different memory blocks but with the same name. The values stored in an array can be accessed by specifying the indexes inside the square brackets starting from 0 and going to the array length - 1([0]...[n-1]). A JavaScript array can be classi
    3 min read
  • Map to Array in JavaScript
    In this article, we will convert a Map object to an Array in JavaScript. A Map is a collection of key-value pairs linked with each other. The following are the approaches to Map to Array conversion: Methods to convert Map to ArrayUsing Spread Operator (...) and Array map() MethodUsing Array.from() M
    3 min read
  • How to use push() & pop() Methods in JavaScript Arrays?
    Arrays are dynamic data structures in JavaScript that have the ability to hold several values of various types. The push() and pop() methods are used for adding and removing elements from an array's last index. 1. Using push() Method in JavaScriptThe push() method is used to add or push the new valu
    2 min read
  • JavaScript Return multiple values from function
    To return multiple values from a function, you can pack the return values as elements of an array or as properties of an object. This approach allows functions to efficiently produce and deliver diverse sets of values, enhancing flexibility and versatility in JavaScript programming. Below are the ap
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences