Technical skill practice
JavaScript indexOf: Find a Value Without Losing Index Zero
Array indexOf returns the first matching index, or −1 when no match exists. Compare its result explicitly with −1. A truthiness test confuses a match at index zero with absence and treats −1 as truthy.
The task
Locate exact route labels in a short timetable, then search again after the first match. This task compares primitive string values. Searching object fields by a condition is a different task for findIndex.
Runnable Node 22 example
const assert = require('node:assert/strict');
const routes = ['harbor', 'ridge', 'harbor', 'park'];
const first = routes.indexOf('harbor');
const second = routes.indexOf('harbor', first + 1);
assert.equal(first, 0);
assert.equal(second, 2);
assert.equal(routes.indexOf('airport'), -1);
assert.equal(routes.indexOf('Harbor'), -1);
assert.equal(routes.indexOf('harbor', 4), -1);
assert.equal(Boolean(first), false);
assert.equal(first !== -1, true);
console.log(`first=${first}; second=${second}; missing=${routes.indexOf('airport')}`);
Expected output and explanation
Harbor appears twice, so the first call returns zero and the second returns two. Starting at first + 1 deliberately excludes the previous match. The original array is only searched; nothing is removed or rearranged.
The capitalized label does not match the lower-case value. Decide whether exact case is the intended contract before normalizing input. The check starting at the array length demonstrates that a start position beyond the available elements cannot find a match.
Output from the example
first=0; second=2; missing=-1
Pitfall to check
Never write if (routes.indexOf(label)) to mean “found.” Inspect index !== -1 before using the number as an array position. Otherwise a missing result can silently select an unintended value when combined with other indexing logic.
Questions, answered
Can indexOf match a newly created object with the same fields?
It compares object identity, not field-by-field equality. Use a predicate search when the match is defined by record content.
Sources and examples
ResumizeAI team. Examples are fictional teaching material, not customer results. Replace sample details with your own facts.
Your experience. A complete resume.
Build in Resumize with ATS-friendly templates, guided editing and a live preview. Start free, then upgrade when you need more.
Free account required. Free-plan PDF exports include a watermark.