1

I tried using instanceof but it can't differentiate between {}, [], and Date.

For example, If I want to make an if tree that goes like this:

function foo(someVar){
  if (/*someVar is an {}*/) {
  } else if (/*someVar is an []*/) {
  } else { //someVar could be a String or a Date or anything
  }
}

How do I write that first if condition? Any help would be appreciated, thank you!

Matt Hauff
  • 65
  • 7
  • See https://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object – simmer Jul 16 '20 at 03:23
  • I don't think they are looking to check empty object, but instead tell a "plain" object from an array from one with methods? There is really no such thing as a "plain vanilla javascript object", but I guess you could check the properties to see if any other them are functions... – NSjonas Jul 16 '20 at 03:26
  • There was some information in the link that @simmer sent that was helpful. I could write the first condition as `if (Object.getPrototypeOf(someVar) === {})`. Thank you very much! – Matt Hauff Jul 16 '20 at 03:50
  • Actually `if(someVar.constructor === Object)` is correct, my comment above did not actually work. – Matt Hauff Jul 16 '20 at 04:15

3 Answers3

1

The first thing that comes to mind to check if something is a 'plain object' is to see if it doesn't have a prototype.

So I think I would write this as:

function foo(someVar){
  if (typeof "someVar" === 'object' && someVar.prototype === undefined) {

  } else if (Array.isArray(someVar)) {

  } else {

  }
}
Evert
  • 93,428
  • 18
  • 118
  • 189
0

This has been answered in separate threads

Date How to check whether an object is a date?

Array How to detect if a variable is an array

Object Check if a value is an object in JavaScript

risingBirdSong
  • 198
  • 3
  • 9
0

to check if The value is of type array you could use Array.isArray() ex:

var first=Array.isArray([1,'fruits',3])
var second=Array.isArray('foo')
console.log(first)
console.log(second)

To check if The value is of type object things get a little bit difficult since type object is an umbrella for too many types like Function,array... but you could use this function, it's by no means is going to work for all types since it doesn't exclude all types but it excludes most of them

 ob=[]
function isObject(obj) {
   if(obj === Object(obj)){
  return Array.isArray(obj)?false:(typeof obj === 'function'?false
  :(Object.prototype.toString.call(obj) === '[object Date]'?false
  :(Object.prototype.toString.call(obj) === '[object Number]'?false
  :(Object.prototype.toString.call(obj) === '[object Math]'?false:true))))}
  else 
  return false
}
console.log(isObject(ob))

To check for type date you could use this

Object.prototype.toString.call(obj) === '[object Date]
Sven.hig
  • 4,449
  • 2
  • 8
  • 18