Testing for typeof array

The usual typeof method isn't very useful for arrays. The 'instanceof' method tests the array to see if it is an instance of the 'Array' constructor, which it is! This will return true or false.

by peterbenoit

JavaScript

// test data
var myArray = [];

// the usual typeof isn't very useful
console.log(typeof myArray);

// this instance of method tests the array
// to see if it is an instance of the 'Array'
// constructor, which it is!

// essentially, see if an object has a property
console.log(myArray instanceof Array)

var color1 = new String("green");
console.log(color1 instanceof String); // returns true
var color2 = "coral"; //no type specified
console.log(color2 instanceof String); // returns false (color2 is not a String object)
var p = new Object("Jon");
console.log(p instanceof Object);