JS tidbit: Never be confused about integer Array access with increments again.

Photo by Ben White on Unsplash

JS tidbit: Never be confused about integer Array access with increments again.

Confusing title I know, naming stuff is hard...

I'll keep this short. Ever seen a code snippet where an integer variable was initialized and used to access an array like this:

const funArray = ['This', 'should', 'be', 'fun']
let i = 0;
let j = 0;

console.log({a:funArray[i++]}) //what would this be?
console.log({b:funArray[++i]})// how about this, hazard a guess?
console.log({c:funArray[++j]})// this one nko?

It can sometimes get confusing, but here's what you should always remember:

  • If the ++ is after the integer variable in such a situation, the variable is incremented AFTER its initial value has been used to access the Array.

  • If the ++ is before the integer variable, the variable is incremented first before being used to access the Array.

//The answers! Hope you got them right!
const funArray = ['This', 'should', 'be', 'fun']
let i = 0;
let j = 0;

console.log({a:funArray[i++]}) 
// ans: {a:'This'}

console.log({b:funArray[++i]})
// ans: {b:'be'} 
//remember i has been incremented to 1, this increments it again to 2 // before funArray is accessed making it funArray[2]

console.log({c:funArray[++j]})
//ans: {c: 'should'}

C'est fini 🤌🏽✨