JavaScript Glossary - Lesson #5

JavaScript Array .some() Method

This method checks if any of the elements contained in an array passes a set test. If at least one of the elements passes this test, true is returned. This method only returns a Boolean.

js
const result = [10, 20, 30, 40, 3].some(function(number) {
  return number < 10;
})
js
// Create new array
const array = [2, 5, 10, 8, 20]

// Create test function
const testFunction = number => number % 5 === 0

// Apply function
const result = array.some(testFunction)

// Display result
console.log(result) // true

The some() method:

  • Takes a callback function that is called once for each element.
  • Runs each element against the set test.
  • Returns true if any of the elements pass the test and false if none of them do.
js
const result = array.some(callback(element[, index[, array]])[, thisArg])

callback (function, required) The function that executes each of the elements of the array. The callback function is required and can take three parameters:

  • element: this is the element currently being executed - required.
  • index: the index of the current item - optional.
  • array: the array that is currently being processed - optional.

thisArg This is an argument passed to be used as the this value in the callback - optional

A boolean value of true or false is returned once the test is passed or failed respectively.

js
// create a string
const names = ['John', 'Peter', 'Mary'];
const firstName = 'John'

const hasMyName = names.some(name => name === firstName);
//Output: 'John'

Used when checking if any elements within an array matches a test.

js
// Array of objects
const users = [
  { firstName: 'Peter', lastName: 'Parker' }, 
  { firstName: 'Harry' }
];

// Verify properties of an object
let hasLastName = users.some(function(user) {
  return !!user.lastName;
})

console.log(hasLastName);
// output: true

Want to improve your coding and design skills?

I'm continually researching the best practices and tools for coding.
Join 50,000+ developers looking to make cool stuff.

We value your privacy. 1-click unsubscribe.

Chris Sev

Chris Sev

Chris Sev is the co-founder of Better Dev. Coding better every day. Previously he created Scotch.io which was acquired.

Comments

What did you think of the article? Let us know!
(these comments are powered by GitHub issues and use 0 trackers)