# Array.at vs length - 1

## Description

Comparison of Array.at vs length - 1.

## Setup

``````// We cannot use floating point numbers, since their operations are not actually associative, so we make them all integers
let array = new Array(100000).fill(0).map(() => ~~(Math.random() * 100));

let sum = array.reduce((lhs, rhs) => lhs + rhs);

``````

## Teardown

``array.length = 0;``

## Test runner

Testing in
TestOps/sec
Backwards sum with .length
``````let mySum = 0;
for(let i = 0; i < array.length; i++) {
mySum += array[array.length - 1 - i];
}

if(mySum != sum) {
throw new Error("Uhhh")
}``````
Backwards sum with .at
``````let mySum = 0;
for(let i = 0; i < array.length; i++) {
mySum += array.at(-i);
}

if(mySum != sum) {
throw new Error("Uhhh")
}``````
Forwards with .length
``````let mySum = 0;
for(let i = 0; i < array.length; i++) {
mySum += array[i];
}

if(mySum != sum) {
throw new Error("Uhhh")
}
``````
Forwards with cached .length
``````let mySum = 0;
for(let i = 0, len = array.length; i < len; i++) {
mySum += array[i];
}

if(mySum != sum) {
throw new Error("Uhhh")
}``````
Forwards with let of
``````let mySum = 0;
for(let item of array) {
mySum += item;
}

if(mySum != sum) {
throw new Error("Uhhh")
}
``````
Forwards with var of
``````let mySum = 0;
for(var item of array) {
mySum += item;
}

if(mySum != sum) {
throw new Error("Uhhh")
}``````
Forwards with const of
``````let mySum = 0;
for(const item of array) {
mySum += item;
}

if(mySum != sum) {
throw new Error("Uhhh")
}``````