0

When working in JavaScript / Typescript, often times occur when i need to check a length exists or if a value is true or false.

The main question is, is there any difference in performance or behaviour between checking as follows...

const data = ['hello', 'good', 'day'];
(data.length) // true 
(data.length > 0) // also true

much like

const booleanValue = false;
(!booleanValue) // true 
(booleanValue === false)  //also true

is there a best way to do this or does it all boil down to readability.

devDan
  • 5,969
  • 3
  • 21
  • 40
  • 2
    Readability; the difference is negligible. If you need to optimise at this level, profiling beats assumptions, always (and what's fastest changes with engine type and version, as they too get optimised,) – Amadan Nov 27 '18 at 08:36
  • Have a look at this: https://softwareengineering.stackexchange.com/questions/12807/make-a-big-deal-out-of-true – Mariyan Nov 27 '18 at 08:39
  • *When you have a boolean value*, `!value` means exactly the same thing as `value === false` in JavaScript, so this applies: https://stackoverflow.com/questions/11831881/if-boolean-false-vs-if-boolean/11831904#11831904 – Ry- Nov 27 '18 at 08:40
  • 1
    Similarly, *when you have an array* and are *also using its length in a boolean context*, `value.length` and `value.length > 0` mean the same thing. But it’s easy to return the wrong type of value, e.g. if you write expressions like `data.length && data[0]` – that entire `&&` expression evaluates to `0` when the array is empty, not `false`. Better to be explicit with the types of your expressions IMO. – Ry- Nov 27 '18 at 08:44

1 Answers1

3

There are differences depending on what you want to achieve ...

for example:

0 == false // true
0 === false // false
undefined == null // true
undefined === null // false
...

Here is a game that will help you understand what are the Boolean relationships in JS: Pedagogical-Game

javimovi
  • 366
  • 2
  • 10