Skip to content

Instantly share code, notes, and snippets.

@djD-REK
Created September 19, 2019 21:12
Show Gist options
  • Save djD-REK/1c773eef779a63ff76971b306ca17c24 to your computer and use it in GitHub Desktop.
Save djD-REK/1c773eef779a63ff76971b306ca17c24 to your computer and use it in GitHub Desktop.
const helloWorldObject = { hello: "world" }
console.log(typeof helloWorldObject) // 'object'
// use Array.isArray or Object.prototype.toString.call
// to differentiate regular objects from arrays
const fibonacciArray = [1, 1, 2, 3, 5, 8]
console.log(typeof fibonacciArray) // 'object'
console.log(Array.isArray(helloWorldObject)) // false
console.log(Array.isArray(fibonacciArray)) // true
// There is another helper function, though it is a bit long:
console.log(Object.prototype.toString.call(helloWorldObject)) // [object Object]
console.log(Object.prototype.toString.call(fibonacciArray)) // [object Array]
// Regular expression have their own native object, RegExp
const myRegExp = /search/
console.log(typeof myRegExp) // 'object'
console.log(myRegExp instanceof RegExp) // true
console.log(Object.prototype.toString.call(myRegExp)) // [object RegExp]
// The Date native object is built-in to JavaScript
const emptyDate = new Date()
const invalidDate = new Date("fail")
console.log(typeof emptyDate) // 'object'
console.log(typeof invalidDate) // 'object'
// Checking for a date is a little trickier
console.log(emptyDate instanceof Date)
console.log(invalidDate instanceof Date)
console.log(Object.prototype.toString.call(invalidDate)) // [object Date]
// Reliable date checking requires a NaN check by checking for NaN:
console.log(invalidDate instanceof Date && !Number.isNaN(invalidDate.valueOf())) // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment