Day 4 of 21 Days of Javascript

Javascript still seems strange to me compared to Python. This is something I'll get over with some muscle memory. Here's a quirk I found today.

Accessing Items in an Array by their Position:

In python we simply use square brackets and this works just fine:

my_items = ['a', 'b', 'c']
print(my_items[1])   # 'b'
print(my_items[-1])  # 'c'

With Javascript we don't have the same liberties. Square brackets can't access negative index positions.

We can only use [] for with index positions of a positive number. For negative numbers (i.e. reverse indexing), we have to use .at() . I'm inclined to always use the latter because it works with positive and negative indexes, and it's compatible with both arrays and strings. Sample code below.

const arr = [10, 20, 30];
arr[0];     // returns 10
arr.at(0);  // returns 10
arr[-1];    // would return undefined
arr.at(-1); // 30 (returns the last element)

const str = "hello";
str[0];     // "h"
str.at(-1); // "o"

const last = arr.at(-1); // gets the last element