Read elements of an array by position.

Array Indexing

array_index.js
const nums = [10, 20, 30, 40];
const i = 1;
const value = nums[i];
const last = nums[nums.length - 1];

console.log("value=" + value);
console.log("last=" + last);
console.log("size=" + nums.length);

Follow the Indexes

  1. nums starts as [10, 20, 30, 40].
  2. The default index i is 1.
  3. nums[i] reads the second value, 20.
  4. nums[nums.length - 1] reads the last value, 40.
  5. The array length is 4, so the script prints size=4. | expression | value | | --- | --- | | nums[1] | 20 | | nums[nums.length - 1] | 40 | | nums.length | 4 |
array-index An array stores values in order, read by a zero-based index. `length` gives the count, so the last index is `length - 1`.

Exercise: array_index.js

Reproduce value=20, last=40, and size=4, then use the pinned i variants 0 and 3 to predict value=10 and value=40 while last and size stay 40 and 4.