So, I have an array of three strings, like this: let arr = ['I', '<3', 'Codecademy']
Then I set the index 5 to equal ‘out of bounds’, assuming that it would throw an error. It did not.
if you print them in a for-of loop, you get undefined values in the gaps, which all makes sense.
But then I tried indexing the last one, using negative numbers like in Python, that’s where it got wierd.
It didn’t get logged to the console using a for-of loop, but did when I used a for-in loop.
What the heck is going on!?
Javascript doesn’t have the option to access items in an array from the end of the array (in brackets) like Python does.
The index -1 in Javascript means that there is no such item in the array.
For example:
console.log([1,2,3].indexOf(3)) // 2
console.log([1,2,3].indexOf(5)) // -1
You can use negative numbers in the .slice()
method, like:
console.log([1,2,3].slice(-2)); // [2, 3]
The index -1 in Javascript means that there is no such item in the array.
But why was I able to successfully assign a value to [-1] of an array?
How did you do that?
This does not work:
const arr = [1,2,3];
arr[-1] = 0;
console.log(arr) // [1, 2, 3]
Try this:
let arr = [0, 1, 2];
arr[-1] = 'helloworld';
arr['helloworld'] = -1;
console.log(arr);
console.log(arr[-1]);
It acts like it’s some kind of string-index in the console:
[0, 1, 2, -1: ‘helloworld’, helloworld: -1]
helloworld
console.log(arr);
from your code still logs [1,2,3]
to the console, so there is no assignment to the array. And you cannot access an item of the array with a negative index like in Python.
But you can assign a value to the key -1 (not the index). This is due to the fact that arrays are (exotic) objects. See this discussion on SO:
1 Like
But you can assign a value to the key -1 (not the index).
Thank you so much for the help!
It’s really weird coming from a Python perspective!
1 Like