Home > Back-end >  Branchless choice of an array in JavaScript
Branchless choice of an array in JavaScript

Time:09-16

In the code below, is it better from the performance and "good language practice" point of view to write f2 instead of f1?

let cond1 = false;
let cond2 = true;

const f1 = () => {
  let arr;
  if(cond1) 
    arr = [1, 2, 3];
  else if(cond2) 
    arr = [4, 5, 6];
  else
    arr = [0, 0, 0];

  console.log(arr);
};
    
const f2 = () => {

  const arr = cond1 && [1, 2, 3] || cond2 && [4, 5, 6] || [0, 0, 0];

  console.log(arr);
};

CodePudding user response:

It depends, in my opinion it is more legible as f1. For more

  • Related