0

Let's walk through a few examples of logic that will calculate which value is smaller:

The basic if-conditional:

let a = 6;
let b = 2;


let smaller = null;
if(a < b) { 
    smaller = a;
  } else {
    smaller = b;
}
console.log(smaller)

Using a Ternary Conditional:


let smaller = a < b ? a : b;
console.log(smaller)

Using Math.min operation

let smaller = Math.min(a,b);
console.log(smaller)

Multiplying Booleans and Number?

let smaller = a*(a<b) + b*(b<=a);
console.log(smaller)
// 6*(6<2) + 2*(2<=6)
// 6*(false) + 2*(true)
// 0 + 2
// 2

Question:

  1. What is this example above called?
  • I don't know of a formal name for this, but it looks like you're *zeroing out a term* via boolean multiplication. This also way, way, way less readable; I cannot say whether it is faster (probably not, though). This approach is probably best used if the person who needs to maintain or understand your code is a known mortal enemy, scorned ex-lover, etc. – apsillers Apr 13 '21 at 16:31
  • On Stack Overflow you are supposed to ask one question at a time, not three. Secondly, asking for resources is nearly always regarded as off topic here. And for your third question: did you perform some benchmarking? That should answer it... – trincot Apr 13 '21 at 16:32
  • @trincot Updated the question. – Rich.Engineer Apr 13 '21 at 16:34
  • trincot's answer is correct in calling it "coercion". However, that's what happens when you operate on two different data types - (at least) one is changed (coerced) into another type for the operation to make sense. With multiplication, all operands will be converted to numbers. However, that's just what happens. If you're asking for a formal name of the *intention* of this code - where you multiply by a boolean in order to use the coercion, then I don't think there is a common name for it. – VLAZ Apr 14 '21 at 05:21

1 Answers1

1

One characteristic in that expression is what is often called coercion. In this case a boolean is coerced into a number during the evaluation. The coercion happens because of the multiplication operator. It would also happen with other arithmetic operators (cf. adding booleans).

It is less efficient than the other options, as here we have 7 operations happening:

  • 2 comparisons
  • 2 conversions of boolean to number
  • 2 multiplications
  • 1 addition
trincot
  • 317,000
  • 35
  • 244
  • 286