Demystifying JavaScript Arrays

Summiting code and mountains. web developer from the Himalayas. Expert in #GraphQL, #TypeScript, Gatsby, #Next.js, and CMS.
Trek, snowboard, rock climb.
Lets break it into steps:
(1) The Basics: Array Access
In JavaScript, arrays are zero-indexed, meaning the first element is accessed with index 0, the second with 1, and so on. So, if we have an array like [9,8,7,6], accessing the element at index 1 should give us 8. That's straightforward, right?
const myArray = [5,9,7,4,6];
const elementAtIndex1 = myArray[1];
// Result: elementAtIndex1 = 9
(2) The Curiosity: Comma Operator
In JavaScript, the comma operator , is a bit of an unsung hero. It evaluates multiple expressions and returns the value of the last one.
Example:
const resultOfCommaOperator = (1, 2);
// Result: resultOfCommaOperator = 2
Here, (1, 2) uses the comma operator. It evaluates 1, then 2, and returns the value of the last one, which is 2. Simple, right?
Unpack the mystery:
Now, let's connect it to our original puzzle:
const finalResult = [5,9,7,5,6][1, 2];
// (1):comma operator will take effect
//(2):original expression now looks like `[5,9,7,4,6][2]`
// Result: finalResult = 7`
The expression [1, 2] inside the square brackets gets evaluated first, and thanks to the comma operator, it becomes just 2. So, our original expression now looks like [5,9,7,5,6][2], and that gives us the result 7.
In essence, the comma operator helped us simplify the array access, turning [1, 2] into a single value, making the final result 7.
JavaScript's quirks can be amusing, and understanding these little intricacies adds to the fun of programming! π


