Skip to content

Linear search

JavaScript loop + return index

Same task in: JavaPHP

Flowchart (ISO 5807)

YesNoStartInput arr, keyi = 0, |arr| − 1, 1arr[i] = keyReturn iReturn −1EndFigure 1 — indexOf

Source code

JavaScript
function indexOf(arr, key) {
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] === key) {
            return i;
        }
    }
    return -1;
}

The editor opens with this code — change it and the chart redraws.

Language
JavaScript
Constructs
loop + return index
Topic
Algorithms
Formats
Word, Visio, draw.io, PDF, SVG

Related examples