lastIndexOf Scans Backwards From an Index
lastIndexOf returns the position of the last match, honoring a fromIndex that starts the backward scan; out-of-range negatives skip the search and return -1.
Code
// lastIndexOf scans from the tail toward the head and returns the last matching index
const events = ['push', 'test', 'push', 'lint', 'push'];
console.log('last push:', events.lastIndexOf('push'));
console.log('first push:', events.indexOf('push'));
console.log('absent:', events.lastIndexOf('deploy'));
// the second argument is the position to start scanning from (inclusive)
console.log('from 2:', events.lastIndexOf('push', 2));
console.log('from -2:', events.lastIndexOf('push', -2));
// negatives are normalized as length + fromIndex; still negative after that skips the whole array and returns -1
console.log('from -100:', events.lastIndexOf('push', -100));
// typical use: locate the last path separator
const path = 'assets/img/logo.svg';
console.log('slash at:', path.lastIndexOf('/'));
console.log('dir:', path.slice(0, path.lastIndexOf('/')));Output
Captured from a sandboxed run of this snippet in the build pipeline.
last push: 4
first push: 0
absent: -1
from 2: 2
from -2: 2
from -100: -1
slash at: 10
dir: assets/imgHow it works
The whole flow works on the top-level bindings: events, path.
What to watch for
- The environment needs no preparation beyond having the interpreter or compiler.
Putting it to use
The demo output is labeled (last push:, first push:, absent:), so each printed line points back to the operation that produced it.
The core lines, annotated
const events = ['push', 'test', 'push', 'lint', 'push'];
const path = 'assets/img/logo.svg';
Interactive Tools for This Topic
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Are there third-party dependencies?
- No. The dependency list is empty; the code stays inside the standard library. Its state lives in module-level bindings: `events`, `path`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.