DEV Community

Yong Liang
Yong Liang

Posted on

Tricky Javascript Stuff 01

1. Javascript has two types of value for empty values - null and undefined. What are the differences for these two?

Undefined -

When the value of a variable is not defined, such that when we create a variable without assigning value, the variable is defined as "undefined". When we check the type with typeOf, the type is also undefined.

Some ways to get undefined:

  1. declare a variable without giving it value
  2. a function returns an empty value
  3. not passing any value to a function's parameter

Javascript has a global variable called undefined and its value and type are shown as undefined.

Null -

Null indicates no value. It is a primitive type and we can assign null to variables. When we check typeOf null it returns as object, however, it's not really an object because we can not add properties to it.

2. == vs === || is the more the better?

The double == comparison operator will not check types, only checks values. It will return true for 8 == "8", even though 8 is a number and "8" is a string.

The tripe === operator will check both type and values. Therefore, 8 === "8" will return false since their types are different.

NaN is a not a number type, along with null and undefined, these three are unique types, and will not equal to other types.

Nan does not even equal to itself. NaN == Nan or NaN === NaN both will return false.

Source: https://www.thatjsdude.com/interview/js2.html#nullVsUndefined

Top comments (0)