Difference between == and ===

In a word, == tries to covert the two values to the same type, and then compare its value.

1
"10" == 10; //true

But === requires the two values to have the same value and the same type:

1
2
"10" === 10; //false
"10" === "10"; //true

== is not so safe to use, so we usually use === or !==.


How to determine if a value is true or false

In JS, whenever we need to transfer a value into a boolean, the value will be determined as truthy or falsy.

It is most commonly used in logical operators like and &&, or ||, not !. When a value is considered truthy it will be converted into true for comparison, vice versa.

Generally speaking, there are only 7 values that will be considered as falsy:

  • false the boolean value false
  • 0 number zero
  • -0 negative 0
  • 0n the bigInt zero
  • "" / '' empty string
  • null
  • undefined
  • NaN not a number

All other values are considered truthy!

If you are not sure if the value is truthy or not, you can use type conversion to find out:

1
console.log(Boolean("0")); //true

However, there are some weird behaviors we may need to memorize:

  1. NaN is NOT equal to anything including itself, so we can only use isNaN to check its type:
    1
    2
    3
    console.log(NaN == NaN); //false
    console.log(Number.isNaN(10/0)); //true
    console.log(typeof NaN); //"number"
  2. null can only be assigned when the programmer explicitly set the value as null, if the variable have no value when declared, it will be undefined.
    1
    2
    3
    4
    console.log(typeof null); //object
    console.log(typeof (undefined)); //undefined
    console.log(null === undefined); //false
    console.log(null == undefined); //true, cause they are all falsy

Short Circuiting

Apart from using &&, || in if or while loop, we can also use them in short circuiting to make things easier.

  1. || OR: returns the first truthy value:
    1
    2
    3
    const userName = '';
    const defaultName = userName || 'Guest';
    console.log(defaultName); // 'Guest'
    It is very useful when we want to set a default value when the input is not valid.
  2. && AND: returns the first falsy value
    1
    console.log(0&&1); //1
  3. ?? Nullish Coalescing Operator: Just like ||, but only checks null and undefined
    1
    2
    3
    4
    console.log(null ?? 'default');      // 'default'
    console.log(undefined ?? 'default'); // 'default'
    console.log(0 ?? 42); // 0 ✅ (NOT replaced!)
    console.log('' ?? 'default'); // '' ✅

With this logic, we can also use logical assignment operators:

1
2
3
a = 0;
a = a || 100;
a ||= 100; //they are the same