I learned a neat trick today if you need to loop through two arrays of the same length from opposite directions — at the same time.

Or if you wanted to start at different ends of the same array and meet in the middle.

Given the two arrays of equal length as such:

`const array1 [2, 4, 6];`

const array2 [3, 5, 9];

Typically I’d use two pointers like this to loop through them in opposite directions:

let indexA = 0; // beginning of array1

let indexB = array2.length - 1; // end of array2while(indexA < array1.length) {

let numA = array1[indexA];

let numB = array2[indexB]; // do something calculating indexA += 1; // move one step forward in array1

index -= 1; // move one step back in array2

}

That’s all well and good, but what if you could actually do this with just one pointer?

Let’s see how.

let idx = 0;while(indexA < array1.length) {

let numA = array1[idx];

let numB = array2[array2.length - idx - 1]; // do something cool idx += 1;

}

Isn’t that fancy!

Why does this work?

Well, the magic is right here, of course:

`array2[array2.length - idx - 1]`

As the value of `idx`

goes up, allowing you to step forward in the first array, the resulting value of `array2.length — idx — 1`

also decreases, giving you a reference to step through the second array from the end index to the start.

Let’s map this out to better see what’s going on here:

`idx formula`

0 3 - 0 - 1 = 2

1 3 - 1 - 1 = 1

2 3 - 2 - 1 = 0

And with that, you are able to step through two arrays from start to finish and finish to start using the same pointer!

# Application

Okay, that’s great and all, but when would you actually use this?

A good example would be the classic palindrome algorithm, which asks you to verify if a given string is a palindrome or not.

One solution for this that has O(n) time complexity and O(1) space complexity involves starting from each end of the string and comparing the value at each index.

If you can get to the center of the string with the characters at each index matching, then you’ve found yourself a palindrome. Otherwise, not.

function isPalindrome(string) {

let len = string.length;

let idx = 0;

while(idx < len / 2) {

if(string[idx] !== string[len - idx - 1]) {

return false;

}

idx += 1;

} return true;

}

Looking for some other JavaScript tips and fun? Please check out some of my other posts: