Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

negative index javascript

// Usually negative indexes do not work

const array = [ 1, 2, 3 ];
const string = "123";

console.log(array[-1]); // -> undefined
console.log(string[-1]); // -> undefined

// However arrays and strings have an `at` property which allows negative indexes
// a negative index will work from the end of the array/string backwards:
Indexes: 0  1  2
Array: [ 1, 2, 3 ]
Indexes:-3 -2 -1

/* Array/String.prototype.at essentially acts like this:
Array.prototype.at = String.prototype.at = function(index) {
	if (index < 0) {
		index = -index;
		while (index >= this.length) {
			index -= this.length;
		}
		if (index === 0) {
			return this[0];
		}
		return this[this.length - index];
	} else {
		while (index >= this.length) {
			index -= this.length;
		}
		return this[index];
	}
};
*/

console.log(array.at(-1)); // -> 3
console.log(string.at(-1)); // -> 3
 
PREVIOUS NEXT
Tagged: #negative #index #javascript
ADD COMMENT
Topic
Name
6+6 =