In js
[ ] == true // false
[ ] ? console.log('a') : console.log('b');
Prints 'a'
Wtf, i lost so much time on this. And i thought i had a grip on js weirdness.

  • 3
    Why do you need to make such comparisons in the first place?

    Also: why not use a language with a sane type system that transpiles to JS?
  • 0
    Why are you comparing an empty array?

    Enlighten us.
  • 1
    We send the names of the colums we want to sort to backend. Should be null or an empty array if no sorting and i thought that if would catch both cases because both are falsely. We are using typescript btw. In hindsight it should be just empty array but i dont want to change too much.
  • 1
    @24th-Dragon 🤔wouldn't you just use .length ?
  • 2
    First mistake is to treat an array as a bool, even if js can coerce it, its not good code and for an array you should check length size.

    Anything else is just asking for problems.

    Yes you save a few chars, but get a lot of problems.
  • 1
    And C has some similar problems where different implementations of the compiler will give different results for the sane code, since the construct is valid code but the result is unpredictable since how the code should be processed is by standard, undefined ;)
  • 1
    @24th-Dragon I believe in your case this is simply how the loose equality operator works, you can see in the link to the spec below. Given y == x, in your case, y is an object and x is a boolean, so the algo defaults to false. (see step 10).

    If you wanted more control, do something like this instead: Boolean([]) == true. Then it will be y is boolean and x is boolean.

    This is a safe operation because all objects are truthy and that will never change.

  • 0
    [] is not true but it's truthy.

    In some way, we could say that
    true !== truthy

    (but !!true && !!truthy)
Add Comment