Search code examples
javascriptarraysobjecttypeof

JS typeOf(array) = 'object'


I'm confused about how JS's typeOf works.

I have an ES6 class with a property array.

When I console.log this property, it shows 'object'.

class Team extends Model {
  constructor(view){
    super(config.saveName + ' Team');
    this.members = [];   // Clearly an array.
  }

  addPerson(person){
    this.members.push(person);
    this.emit('personAdded', person);
  }

  removePerson(person){
    if(this.members.includes(person)){
        this.members.splice(this.members.indexOf(person),1);
        this.emit('personRemoved', person);
    }
  }

  update(newTeam){
    this.members = newTeam;
    this.emit('teamDataChanged', this.members);
  }
}

console.log(typeOf(new Team().members)); // 'object'

Solution

  • In JS everything but primitives are objects. Primitives are : Numbers , Booleans , Null , Undefined , String , Symbol

    The rest are objects (arrays, objects, maps, sets...)

    So typeof [] === "Object" typeof 123 === "number"