@jgCarroll/

arrayIndexOf

JavaScript

A common interview question.

fork
loading
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
console.log([10, 20, 30, 40, 50].indexOf(30)); // logs 2

console.log([{ name: 'Pam' }, { name: 'Kent' }].indexOf({ name: 'Kent' })); // logs -1, meaning that it found nothing. Two objects are never the same. indexOf doesn't see them as being same types.

console.log('hello world'.indexOf('o')); // logs 4. Notice this is a string instead of an array.

console.log([[1], [2], [3], [4]].indexOf([2])); // logs -1, meaning that it found nothing. Two different arrays are never equal.

// ...But, two different variables that both reference the same underlying object will evaluate as equal (as below)

const myArray = [5]
const anotherArray = myArray

console.log([[1], [2], [3], [4], myArray].indexOf(myArray)); // logs 4
console.log([[1], [2], [3], [4], myArray].indexOf(anotherArray)); // logs 4
Native Browser JavaScript