"Writing maintainable JavaScript" - type detection

Variable does not compare with the null

function process(items){
  if(items !== null){
  }
}

items may be 1 or even a string objects, these values are not null and equal
, with one exception, that is, when the expectations are really null

var element = document.getElementById('myDiv');
if(element !== null){
}

If the DOM element does not exist, by document.getElementById () obtained is null

Detecting original value

There are five kinds of JS primitive types: number, string, boolean, undefined and null
detector primitive type is the best choice to use typeof, respectively, will return the string type "number", "string", "boolean", "undefined"
is not recommended typeof detection null, because typeof null as the "Object"
typeof even for an undefined variable is not an error, unset or undefined returns "undefined"

Detection reference type

Value is also called an object reference, among other values are referenced in the original type JS, has a built-in reference type Object, Array, Date, and Error
of typeof return type detecting these references are "object"

Detecting a reference type is the best way to use instanceof operator
instanceof detector configured not only the object constructor, also detects prototype chain

Guess you like

Origin www.cnblogs.com/Grani/p/11355565.html