2
let a = {}
let b = []

typeof a // returns an object
typeof b // returns an object

 a === {} // false
 b === [] // false
 a === b // false

how then can I know if its an array or object, I'm trying to validate user input, where it can either be an array or object but in either Case I don't want the value to be empty

1
  • 2
    Both a === a and b === b are actually true; perhaps you meant that {} === {} and [] === [] are both false (which is expected since === does an object reference comparison, and {} and [] both create new objects) Commented May 10, 2020 at 23:45

4 Answers 4

4

This is really a few questions wrapped up into one. First off, it is counter-intuitive for many that typeof [] is 'object'. This is simply because an Array is an reference type (null, Date instances, and any other object references also have typeof of object).

Thankfully, to know if an object is an instance of Array, you can now use the convenient Array.isArray(...) function. Alternatively, and you can use this for any type of object, you can do something like b instanceof Array.

Knowing if one of these is empty can be done by checking Object.keys(a).length === 0, though for Arrays it's more natural to do b.length === 0.

Checking any two objects variables (including Arrays) with === will only tell you if the two variables reference the same object in memory, not if their contents are equal.

Sign up to request clarification or add additional context in comments.

1 Comment

Array.isArray(o) is a better choice than o instanceof Array since the former only returns true if o is (in specification terms) an exotic array object. For example Array.isArray(Object.setPrototypeOf({}, Array.prototype)) is false while Object.setPrototypeOf({}, Array.prototype) instanceof Array is true.
2

Since both Arrays and Objects share the same type, you can check for instance:

if (b instanceof Array) {

}

Comments

2
if (Array.isArray(a) && a.length === 0) {
  // a is an array and an empty one
}

1 Comment

While this code may provide a solution to problem, it is highly recommended that you provide additional context regarding why and/or how this code answers the question. Code only answers typically become useless in the long-run because future viewers experiencing similar problems cannot understand the reasoning behind the solution.
2

Actually, using typeof for both Objects and Arrays will return Object. There are certain methods in JS to check if a variable is an array or not.

  1. Array.isArray(variableName)
  2. variableName instanceof Array
  3. variableName.constructor === Array

All these Methods will return true if variable is an array else will return false.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.