Skip to content

Instantly share code, notes, and snippets.

@glafarge
Created February 10, 2016 17:59
Show Gist options
  • Save glafarge/64cdfef69cb5d8afc1ba to your computer and use it in GitHub Desktop.
Save glafarge/64cdfef69cb5d8afc1ba to your computer and use it in GitHub Desktop.
Check if variable is Array
/**
* Check whether an object is Array or not
* @type Boolean
* @param {object} subject is the variable that is
* tested for Array identity check
*/
var isArray = (function () {
// Use compiler's own isArray when available
if (Array.isArray) {
return Array.isArray;
}
// Retain references to variables for performance
// optimization
var objectToStringFn = Object.prototype.toString,
arrayToStringResult = objectToStringFn.call([]);
return function (subject) {
return objectToStringFn.call(subject) === arrayToStringResult;
};
}());
console.log( isArray(123) ); // false
console.log( isArray(true) ); // false
console.log( isArray("my little string") ); // false
var obj = {
items: [
{id:1, name:'alpha'},
{id:2, name:'beta'},
{id:3, name:'gamma'},
]
};
console.log( isArray(obj) ); // false
var arr = ["Saab", "Volvo", "BMW"];
console.log( isArray(arr) ); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment