JavaScript Type Coercion

Tram Ho

Working with Javascript, many of you have encountered the following cases:

This is due to the so-called Javascript Type Coercion. Understandably, JS always tries to force the data type. For example:

In the above example, JS would first cast the boolean true to number 1 and then do the addition and get a result of 2.

Using operations with operators like - , * , / , and % will force the data type to return a number .

But with the + operator, it is unlikely that the data type returned will be number because we can use + to do the math OR combine the strings together. So, by default, the operators when using + will prioritize returning string data types.

JS also has another type of data compression that is truthiness. For example, if/else you use if/else with a certain value, then JS can force the data type of that value to true or false .

Most values ​​in JS are cast to true except for 7 values

  • false
  • 0
  • -0
  • NaN
  • ""
  • null
  • undefined These values ​​are to be cast to false
Share the news now

Source : Viblo