indexOf()

The JavaScript indexOf() method loops over an array and returns the index number of the first found element. If a value is not found, it returns -1. This method uses strict equality (===) for comparison.

Syntax

const index = array.indexOf(searchElement, fromIndex);

Parameters:

  • searchElement: The value to search for in the array.
  • fromIndex (optional): The index position to start the search from. Defaults to 0. Negative values count back from the end of the array.

Basic usage

The indexOf() method is used to locate the position of a value in an array. This example finds where a specific topping appears on the menu:

const pizzaToppings = ['Cheese', 'Pepperoni', 'Mushrooms', 'Olives', 'Bacon'];

const olivesPosition = pizzaToppings.indexOf('Olives');
console.log(olivesPosition); // Output: 3

const jalapenoPosition = pizzaToppings.indexOf('Jalapeno');
console.log(jalapenoPosition); // Output: -1 (not found)

Loading code...

const pizzaToppings = ['Cheese', 'Pepperoni', 'Mushrooms', 'Olives', 'Bacon'];

const olivesPosition = pizzaToppings.indexOf('Olives');
console.log(olivesPosition); // Output: 3

const jalapenoPosition = pizzaToppings.indexOf('Jalapeno');
console.log(jalapenoPosition); // Output: -1 (not found)

This example checks if a pizza size is available before placing an order:

const availableSizes = ['Small', 'Medium', 'Large', 'Extra Large'];

const requestedSize = 'Medium';
const sizeIndex = availableSizes.indexOf(requestedSize);

if (sizeIndex !== -1) {
  console.log(`${requestedSize} is available at position ${sizeIndex}`);
} else {
  console.log(`${requestedSize} is not available`);
}
// Output: Medium is available at position 1

Loading code...

const availableSizes = ['Small', 'Medium', 'Large', 'Extra Large'];

const requestedSize = 'Medium';
const sizeIndex = availableSizes.indexOf(requestedSize);

if (sizeIndex !== -1) {
  console.log(`${requestedSize} is available at position ${sizeIndex}`);
} else {
  console.log(`${requestedSize} is not available`);
}
// Output: Medium is available at position 1

The fromIndex parameter

The second parameter allows you to begin the search from a specified position:

const pizzaOrders = ['Margherita', 'Pepperoni', 'Veggie', 'Pepperoni', 'Hawaiian'];

// Find first Pepperoni
const firstPepperoni = pizzaOrders.indexOf('Pepperoni');
console.log(firstPepperoni); // Output: 1

// Find Pepperoni starting from index 2 (Veggie)
const secondPepperoni = pizzaOrders.indexOf('Pepperoni', 2);
console.log(secondPepperoni); // Output: 3

Loading code...

const pizzaOrders = ['Margherita', 'Pepperoni', 'Veggie', 'Pepperoni', 'Hawaiian'];

// Find first Pepperoni
const firstPepperoni = pizzaOrders.indexOf('Pepperoni');
console.log(firstPepperoni); // Output: 1

// Find Pepperoni starting from index 2 (Veggie)
const secondPepperoni = pizzaOrders.indexOf('Pepperoni', 2);
console.log(secondPepperoni); // Output: 3

Using a negative fromIndex value searches from the end of the array:

const dailySpecials = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];

// Start searching from 2 positions before the end
const dayIndex = dailySpecials.indexOf('Wednesday', -3);
console.log(dayIndex);
// Output: 2

Loading code...

const dailySpecials = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];

// Start searching from 2 positions before the end
const dayIndex = dailySpecials.indexOf('Wednesday', -3);
console.log(dayIndex);
// Output: 2

Finding all occurrences

Since indexOf() only returns the first match, you can use a loop to find all positions. This example will continue looping through the array until the requested value is not found (-1):

const orderHistory = ['Margherita', 'Hawaiian', 'Margherita', 'Pepperoni', 'Margherita'];

const findAllPositions = (array, value) => {
  const positions = [];
  let currentIndex = array.indexOf(value);

  while (currentIndex !== -1) {
    positions.push(currentIndex);
    currentIndex = array.indexOf(value, currentIndex + 1);
  }

  return positions;
};

const margheritaOrders = findAllPositions(orderHistory, 'Margherita');
console.log(margheritaOrders); // Output: [0, 2, 4]

Loading code...

const orderHistory = ['Margherita', 'Hawaiian', 'Margherita', 'Pepperoni', 'Margherita'];

const findAllPositions = (array, value) => {
  const positions = [];
  let currentIndex = array.indexOf(value);

  while (currentIndex !== -1) {
    positions.push(currentIndex);
    currentIndex = array.indexOf(value, currentIndex + 1);
  }

  return positions;
};

const margheritaOrders = findAllPositions(orderHistory, 'Margherita');
console.log(margheritaOrders); // Output: [0, 2, 4]

Strict equality comparison

The indexOf() method uses strict equality (===), so type matters:

const pizzaPrices = [10, 12, '15', 18, 20];

// Searching for number 15
console.log(pizzaPrices.indexOf(15)); // Output: -1 (not found because '15' is a string)

// Searching for string '15'
console.log(pizzaPrices.indexOf('15')); // Output: 2

Loading code...

const pizzaPrices = [10, 12, '15', 18, 20];

// Searching for number 15
console.log(pizzaPrices.indexOf(15)); // Output: -1 (not found because '15' is a string)

// Searching for string '15'
console.log(pizzaPrices.indexOf('15')); // Output: 2

Removing elements by value

A common use case for indexOf() is removing a specific item from an array:

const cartItems = ['Margherita', 'Mushroom', 'Cola', 'Pepperoni'];

const removeDrinks = (cart, itemToRemove) => {
  const index = cart.indexOf(itemToRemove);
  if (index !== -1) {
    cart.splice(index, 1);
  }
  return cart;
};

console.log(removeDrinks(cartItems, 'Cola'));
// Output: ['Margherita', 'Mushroom', 'Pepperoni']

Loading code...

const cartItems = ['Margherita', 'Mushroom', 'Cola', 'Pepperoni'];

const removeDrinks = (cart, itemToRemove) => {
  const index = cart.indexOf(itemToRemove);
  if (index !== -1) {
    cart.splice(index, 1);
  }
  return cart;
};

console.log(removeDrinks(cartItems, 'Cola'));
// Output: ['Margherita', 'Mushroom', 'Pepperoni']

Checking for duplicates

You can use indexOf() to detect if an array contains any duplicate values:

const toppingSelection = ['Cheese', 'Pepperoni', 'Mushrooms', 'Pepperoni', 'Olives'];

const hasDuplicates = (array) => {
  return array.some((item, index) => array.indexOf(item) !== index);
};

console.log(hasDuplicates(toppingSelection)); // Output: true

// Find which items are duplicated
const findDuplicates = (array) => {
  return array.filter((item, index) => array.indexOf(item) !== index);
};

// Locate the duplicate value
console.log(findDuplicates(toppingSelection)); // Output: ['Pepperoni']

Loading code...

const toppingSelection = ['Cheese', 'Pepperoni', 'Mushrooms', 'Pepperoni', 'Olives'];

const hasDuplicates = (array) => {
  return array.some((item, index) => array.indexOf(item) !== index);
};

console.log(hasDuplicates(toppingSelection)); // Output: true

// Find which items are duplicated
const findDuplicates = (array) => {
  return array.filter((item, index) => array.indexOf(item) !== index);
};

// Locate the duplicate value
console.log(findDuplicates(toppingSelection)); // Output: ['Pepperoni']

Practical example: order queue management

const orderQueue = ['ORD001', 'ORD002', 'ORD003', 'ORD004', 'ORD005'];

const checkOrderStatus = (orderId) => {
  const position = orderQueue.indexOf(orderId);

  if (position === -1) {
    return `Order ${orderId} not found in queue`;
  } else if (position === 0) {
    return `Order ${orderId} is being prepared now`;
  } else {
    return `Order ${orderId} is #${position + 1} in queue (${position} orders ahead)`;
  }
};

console.log(checkOrderStatus('ORD003'));
console.log(checkOrderStatus('ORD001'));
console.log(checkOrderStatus('ORD006'));

Loading code...

const orderQueue = ['ORD001', 'ORD002', 'ORD003', 'ORD004', 'ORD005'];

const checkOrderStatus = (orderId) => {
  const position = orderQueue.indexOf(orderId);

  if (position === -1) {
    return `Order ${orderId} not found in queue`;
  } else if (position === 0) {
    return `Order ${orderId} is being prepared now`;
  } else {
    return `Order ${orderId} is #${position + 1} in queue (${position} orders ahead)`;
  }
};

console.log(checkOrderStatus('ORD003'));
console.log(checkOrderStatus('ORD001'));
console.log(checkOrderStatus('ORD006'));

Limitations with objects

The indexOf() method compares objects by reference for objects not value:

const pizzaMenu = [
  { name: 'Margherita', price: 10 },
  { name: 'Pepperoni', price: 12 }
];

// This won't work, using a different object reference
const searchPizza = { name: 'Margherita', price: 10 };
console.log(pizzaMenu.indexOf(searchPizza)); // Output: -1

// Same reference will work
const margherita = pizzaMenu[0];
console.log(pizzaMenu.indexOf(margherita)); // Output: 0

Loading code...

const pizzaMenu = [
  { name: 'Margherita', price: 10 },
  { name: 'Pepperoni', price: 12 }
];

// This won't work, using a different object reference
const searchPizza = { name: 'Margherita', price: 10 };
console.log(pizzaMenu.indexOf(searchPizza)); // Output: -1

// Same reference will work
const margherita = pizzaMenu[0];
console.log(pizzaMenu.indexOf(margherita)); // Output: 0

For searching objects by property values, use findIndex() instead.

When to use indexOf() vs. other methods

Use indexOf() when:

  • You want to check if both and item exists and also require the index position.
  • You need to locate the position of a primitive value (string, number, boolean).
  • You want to specify the array start position.

Consider using other methods when:

  • You only need to check if a value exists (use includes()).
  • You need to find objects by property values (use findIndex()).
  • You need the element rather than the index position (use find()).
  • You need the last occurrence of a value (use lastIndexOf()).

Conclusion

The indexOf() method provides a way to locate primitive values within arrays, using stric equality. By returning the index position of the first match (or -1 if not found), it enables you to determine both the existence and index position of values. While it works well for primitive types, remember that object comparison is done by reference, making findIndex() a better choice when searching for object properties.