-1

Function returns the type of object

 function objOrLis(obj) {
    if (typeof obj == "object") {
        poss = "object"
        try {
            for (let i of obj) {
                poss = "list"
            }
        }
        catch {
            poss = "object"
        }
        return poss
    }
    else {
        let c = typeof obj
        return c
    }
}
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • `for (let i of obj)` will be executed 0 times for empty arrays, thus never executing `pass = "list"`. If you put that statement _after_ the loop, it should work, because if `for (let i of obj)` throws an error, anything after that (within the `try` block) is not going to get executed. However, note that JS doesn’t really have “lists”. Arrays can be checked with `Array.isArray`; what you’re checking are _iterables_. And iterables are easier checked with `if(Symbol.iterator in obj)`. Note that there are also array-likes which are not always the same thing. These have a numeric `length` property. – Sebastian Simon Oct 22 '21 at 03:39

3 Answers3

2

Use Array.isArray() to identify arrays:

function objOrLis(obj) {
  return Array.isArray(obj)
    ? 'list'
    : typeof obj
}

console.log(objOrLis([]))
console.log(objOrLis({}))
console.log(objOrLis(1))
console.log(objOrLis('str'))
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
1

Object.prototype.toString gives different results

const array = [1,2,3];
const set = new Set(array);
const map = {a:1,b:2,c:3};

console.log(Object.prototype.toString.call(array));
console.log(Object.prototype.toString.call(set));
console.log(Object.prototype.toString.call(map));
ProDec
  • 5,390
  • 1
  • 3
  • 12
-1

An ES6 one liner to differentiate between an array and an object.

const objectOrList = (o) => (o instanceof Array ? "list" : (o instanceof Object ? "object" : typeof o))

const objectOrList = (o) => (o instanceof Array ? "list" : (o instanceof Object ? "object" : typeof o));

console.log(objectOrList([]));
console.log(objectOrList({}));
console.log(objectOrList(1));
console.log(objectOrList("string"));
Lakshaya U.
  • 1,089
  • 1
  • 5
  • 21
  • The flaw with this approach is that the `Array` constructor is a different object in different windows, such as created for frames and child windows opened in script. Hence testing objects as instances of "Array" fails if the object was passed between windows. This failure is the _reason_ `Array.isArray` was introduced. And I nearly forgot, objects created with a `null` value prototype are not instances of `Object` either. – traktor Oct 22 '21 at 04:04