0
var _={};

_.bullets='1,2,3';

console.log(typeof bullets);

string

console.log(_.bullets);

var bullets=_.bullets.split(',');

console.log(bullets);    //REF 1

["1", "2", "3"]

console.log(typeof bullets);

object

Why is it not array? I can't figure out what I am doing wrong here

UPDATE

console.log([1,2,3]);
console.log(bullets);    //REF 1

[1, 2, 3]

["1", "2", "3"]

What is the difference (one is a string one is a number?)

3
  • stackoverflow.com/questions/4775722/check-if-object-is-array Commented Jan 22, 2014 at 15:03
  • 1
    The difference between [1,2,3] and ["1", "2", "3"] is that one is an array with 3 numbers, and one is an array with three strings. Commented Jan 22, 2014 at 15:08
  • 2
    typeof [] === "object" - the only objects where typeof does not yield "object" are functions. Commented Jan 22, 2014 at 15:09

4 Answers 4

3

typeof never returns 'array'. For instances of Array, it returns 'object':

Table 20 — typeof Operator Results

  • Undefined : "undefined"
  • Null : "object"
  • Boolean : "boolean"
  • Number : "number"
  • String : "string"
  • Object (native and does not implement [[Call]]) : "object"
  • Object (native or host and does implement [[Call]]) : "function"
  • Object (host and does not implement [[Call]]) : Implementation-defined except may not be "undefined", "boolean", "number", or "string".

Source: ECMAScript spec

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

Comments

2

Use Array.isArray(a) or a instanceof Array.

Arrays are objects, so typeof returns object.

Comments

1

Technically typeof fits for primitive types while instanceof fits for reference types.

If you use typeof for some reference types (Array, Object), it will return "object". Function is the third reference type; it behaves differently (typeof wise) as it will return "function" when typeof new Function().

Based on your example you can deduce that string is a primitive type in JavaScript as typeof "blabla" === string (which returns true). Yes that's something curious if you come from a traditional strongly typed language such as Java or C#.

Comments

0

typeof returns 'object' when supplied array values. To test for an array you can do something like this (from JavaScript the Good Parts):

var is_array = function (value) {
     return value &&
     typeof value === 'object' &&
     typeof value.length === 'number' &&
     typeof value.splice === 'function' &&
     !(value.propertyIsEnumerable('length'));
};

1 Comment

This is called duck-typing. If it splices like a duck, it's a duck.

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.