typeof and instanceof on in JavaScript

JavaScript, typeofand instanceofit can be used to determine the type of data, when to choose typeof? When choosing instanceof?

typeofOperators

typeofOperator returns the following values ​​are

  • Primitive data types
typeof 123 // "number"
typeof '123' // "string"
typeof false // "boolean"
  • Function Type
function f() {}
typeof f
// "function"
  • undefined
typeof undefined
// "undefined"
var x
typeof x
// "undefined
  • Object
typeof window // "object"
typeof {} // "object"
typeof [] // "object"
typeof null // "object

instanceofOperators

instanceofIt is to determine whether the instance variable of an object, the return value is true or false.

var o = {};
var a = [];

o instanceof Array // false
a instanceof Array // true
a instanceof Object // true

typeof array [] {} and the target values are returned Object, arrays and objects can not be distinguished, but instanceofcan be distinguished.

For when to use typeofandinstanceof

  • When the variable is possible to use typeof operator when the undefined
alert(typeof undefinedVariable); // alerts the string "undefined"
alert(undefinedVariable instanceof Object); // throws an exception
  • When used as a variable may be null when the instanceofoperator
var myNullVar = null;
alert(typeof myNullVar ); // alerts the string "object"
alert(myNullVar  instanceof Object); // alerts "false"

link:
https://stackoverflow.com/questions/899574/what-is-the-difference-between-typeof-and-instanceof-and-when-should-one-be-used

https://www.jianshu.com/p/1216b1f429fb

Guess you like

Origin www.cnblogs.com/yuanchao-blog/p/JavaScript.html