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!?
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]
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]
let arr = [0, 1, 2];
arr[-1] = 'helloworld';
arr['helloworld'] = -1;
It acts like it’s some kind of string-index in the console:
[0, 1, 2, -1: ‘helloworld’, helloworld: -1]
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:
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!