1

I understand strict type comparison with '===' and '!==' checking if the value and type are equal.

Comparing with '==' or '!=' will cast the variable to the value to be compared. So for example comparing a variable 'id' with null will cast 'id' value, meaning 0, '', null, undefined equals null.

I would like to know if the following two ways of writing a condition are really completely the same:

if (id != null) {}

and on the other hand

if (!id) {}
LuJaks
  • 1,047
  • 1
  • 10
  • 21
  • what happens if `var id = 1;`? – luk2302 Feb 03 '21 at 13:24
  • You can use `if (!x)` to check any falsy value, but it doesn't work reversed, for example `0 == null` is false. – Teemu Feb 03 '21 at 13:25
  • 1
    *"0, '', null, undefined equals null"* is incorrect. Only `undefined` and `null` satisfy the `x == null` loose comparison. `id != null` -> Everything except undefined and null. `!id` -> Everything except [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) values (0, null, undefined, '', NaN etc) – adiga Feb 03 '21 at 13:25
  • 1
    This might help: [All falsey (and truthy) values in JavaScript](https://stackoverflow.com/questions/19839952/all-falsey-values-in-javascript) – Turnip Feb 03 '21 at 13:27

0 Answers0