0

I'm following a web performance course where the following piece of code is shared:

// Interesting operator

const objects = [{ a: 1 }, { a: 2 }, { a: 3 }, { a: 4 }];
let iterations = 10;
while (iterations--) {
  let sum = 0;
  const obj = objects[iterations & 3];
  console.log(obj.a);
}

I've never seen anything like objects[iterations & 3] before. The loop will iterate through the array but it never goes out of bounds. I searched through MDN and other websites for more information but I couldn't find this operator.

Any pointers? Thanks!

Here is the example in code sandbox: https://codesandbox.io/s/dreamy-snowflake-gcmml?fontsize=14

jorgevenegas
  • 101
  • 1
  • 5
  • `&` is bitwise AND. Was the code-writer *trying* to confuse readers of his code? Better to use `% 4`, it's a lot more intuitive. – CertainPerformance Nov 06 '19 at 01:40
  • Regarding MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_AND – Bergi Nov 06 '19 at 01:41

0 Answers0