Search code examples
javascriptbitwise-operatorsconditional-operator

Understanding the use of bitwise-operator in ternary-operator


I'm just learning how to code and while studying sorting algorithms I was asked to "see if you can combine the two lines in your if and else blocks into one line to make your code look a little cleaner."

const merge = (leftArray, rightArray) => {
  const sortedArray = [];
  while (leftArray.length > 0 && rightArray.length > 0) {
    if (leftArray[0] < rightArray[0]) {
      sortedArray.push(leftArray[0]);
      leftArray.shift();
    } else {
      sortedArray.push(rightArray[0]);
      rightArray.shift();
    }
  }

The first thing that came to my mind was to use ternary operator, and then, for some reason (never saw that being done before), I thought that I could just take the two actions for every condition, join them with '&&' and that would work.

But I had a typo!! I wrote '&' instead of '&&', and for my surprise, even with that it worked as intended. But I have no idea why, can't find anything that explains how this actually works and why. (Below is all the code and the part I re-wrote).

const mergeSort = (startArray) => {
  const length = startArray.length;
  if (length === 1) {
    return startArray;
  }
  
  const mid = Math.floor(length / 2);
  const leftArray = startArray.slice(0, mid);
  const rightArray = startArray.slice(mid, length);

  return merge(mergeSort(leftArray), mergeSort(rightArray))
}

const merge = (leftArray, rightArray) => {
  const sortedArray = [];
  while (leftArray.length > 0 & rightArray.length > 0) {
    leftArray[0] < rightArray[0] ? 
    sortedArray.push(leftArray[0]) & leftArray.shift() : 
    sortedArray.push(rightArray[0]) & rightArray.shift()
  }
  
  return sortedArray.concat(leftArray).concat(rightArray);
}

I would appreciate if some could shed some light to this.


Solution

  • && is a comparator. In this case, & and && will do the exact same (outside of possibly a few edge cases), but that's mostly because you're not using them as intended. Let me explain.

    & is a bitwise operator. It takes two numbers and runs a Bitwise AND on each bit in each number to generate a result. The reason your code works is because you don't actually do anything with the output of your Bitwise AND. Instead, your goal is just to run two functions.

    What you're telling JS to do here is to take the outputs of these two functions and AND them together. But, in order to get the outputs of the functions, JS has to execute them. So when it sees this block, it calls both functions, and then it also takes the Bitwise AND of the outputs (though you don't ever see this because you aren't doing anything with the outputs). In your case, this works fine because both functions end up getting called, and you get the expected output.