Menu
Coddy logo textTech

The Find & FindIndex Method

Part of the Logic & Flow section of Coddy's JavaScript journey — lesson 58 of 65.

The find() method returns the first element in an array that satisfies a provided testing function. If no element is found, it returns undefined.

The findIndex() method is similar but returns the index of the first matching element instead of the element itself. If no element is found, it returns -1.

Basic syntax:

array.find(callback(element[, index[, array]]))
array.findIndex(callback(element[, index[, array]]))

Simple example with find():

const numbers = [5, 12, 8, 130, 44];
const found = numbers.find(num => num > 10);
console.log(found);
// 12 (first number greater than 10)

Same example with findIndex():

const numbers = [5, 12, 8, 130, 44];
const foundIndex = numbers.findIndex(num => num > 10);
console.log(foundIndex);
// 1 (index of first number greater than 10)

Finding objects in an array:

const inventory = [
	{name: 'apples', quantity: 2},
	{name: 'bananas', quantity: 0},
	{name: 'oranges', quantity: 5}
];

// Using find
const result = inventory.find(item => item.name === 'bananas');
console.log(result); // {name: 'bananas', quantity: 0}

// Using findIndex
const index = inventory.findIndex(item => item.name === 'bananas');
console.log(index); // 1

Try it yourself

This lesson doesn't include a code challenge.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow