Skip to content

Instantly share code, notes, and snippets.

@zmts
Last active November 23, 2020 22:25
Show Gist options
  • Select an option

  • Save zmts/35dc0e33c2d972dd33f661dcf727962b to your computer and use it in GitHub Desktop.

Select an option

Save zmts/35dc0e33c2d972dd33f661dcf727962b to your computer and use it in GitHub Desktop.
Object type vs Array type. Handle JavaScript types

Object type vs Array type. Handle JavaScript types

Object.prototype.toString.call(true) // [object Boolean]
Object.prototype.toString.call('hello') // [object String]
Object.prototype.toString.call(10) // [object Number]
Object.prototype.toString.call({}) // [object Object]
Object.prototype.toString.call([]) // [object Array]
Object.prototype.toString.call(null) // [object Null]
Object.prototype.toString.call(undefined) // [object Undefined]
Object.prototype.toString.call(somePromise) === '[object Promise]'

https://github.com/d-mon-/typeof--/blob/master/index.js

About perfomance

console.time('typeof')
for (let i = 0; i < 10000; i++) {
  typeof 100 === 'number'
}
console.timeEnd('typeof')

console.time('prototype.toString')
for (let i = 0; i < 10000; i++) {
  Object.prototype.toString.call(100) === '[object Number]'
}
console.timeEnd('prototype.toString')
typeof: 0.228ms
prototype.toString: 2.531ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment