Use of the identity function in JavaScript - javascript

I use the identity function in all my JavaScript programs:
function identity(value) {
return value;
}
The reason is that I often need differentiate between primitives types (undefined, null, boolean, number and string) and object types (object and function) as returned by the typeof operator. I feel using the indentity function for this use case very succuint:
if (new identity(value) == value); // value is of an object type
if (new identity(value) != value); // value is of a primitive type
The identity function is much smaller and simpler than the following code:
function isObject(value) {
var type = typeof value;
return type == "object" || type == "function";
}
However on reading my code a friend of mine complained that my hack is misleading and more computationally expensive than the above alternative.
I don't want to remove this function from any of my programs as I believe it's an elegant hack. Then again I don't write programs solely for myself. Is there any other use case for the identity function in JavaScript?

IMHO:
new identity(value) == value
means absolutely nothing and without extra comment I would have to think for a while to figure out what the intent was. On the other hand:
isObject(value)
is obvious from the very beginning, no matter how it is implemented. Why can't you use your hack inside a function named isObject()?
BTW More suited for http://codereview.stackexchange.com.

I updated my "speedtest" to test if the right results are returned … they aren't:
If you compare with new identity(x) == x, then null is deemed an object. === works, though.
Such pitfalls speak in favor of the isObject(...) solution.
If you compare === 'object'/'function' in the isObject code, then it will be double as fast as your original implementation, and almost a third faster than new identity(x) === x.

Related

how to use map function when there are no records Reactjs [duplicate]

How do I check if a variable is an array in JavaScript?
if (variable.constructor == Array)
There are several ways of checking if an variable is an array or not. The best solution is the one you have chosen.
variable.constructor === Array
This is the fastest method on Chrome, and most likely all other browsers. All arrays are objects, so checking the constructor property is a fast process for JavaScript engines.
If you are having issues with finding out if an objects property is an array, you must first check if the property is there.
variable.prop && variable.prop.constructor === Array
Some other ways are:
Array.isArray(variable)
Update May 23, 2019 using Chrome 75, shout out to #AnduAndrici for having me revisit this with his question
This last one is, in my opinion the ugliest, and it is one of the slowest fastest. Running about 1/5 the speed as the first example. This guy is about 2-5% slower, but it's pretty hard to tell. Solid to use! Quite impressed by the outcome. Array.prototype, is actually an array. you can read more about it here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
variable instanceof Array
This method runs about 1/3 the speed as the first example. Still pretty solid, looks cleaner, if you're all about pretty code and not so much on performance. Note that checking for numbers does not work as variable instanceof Number always returns false. Update: instanceof now goes 2/3 the speed!
So yet another update
Object.prototype.toString.call(variable) === '[object Array]';
This guy is the slowest for trying to check for an Array. However, this is a one stop shop for any type you're looking for. However, since you're looking for an array, just use the fastest method above.
Also, I ran some test: http://jsperf.com/instanceof-array-vs-array-isarray/35 So have some fun and check it out.
Note: #EscapeNetscape has created another test as jsperf.com is down. http://jsben.ch/#/QgYAV I wanted to make sure the original link stay for whenever jsperf comes back online.
You could also use:
if (value instanceof Array) {
alert('value is Array!');
} else {
alert('Not an array');
}
This seems to me a pretty elegant solution, but to each his own.
Edit:
As of ES5 there is now also:
Array.isArray(value);
But this will break on older browsers, unless you are using polyfills (basically... IE8 or similar).
There are multiple solutions with all their own quirks. This page gives a good overview. One possible solution is:
function isArray(o) {
return Object.prototype.toString.call(o) === '[object Array]';
}
In modern browsers (and some legacy browsers), you can do
Array.isArray(obj)
(Supported by Chrome 5, Firefox 4.0, IE 9, Opera 10.5 and Safari 5)
If you need to support older versions of IE, you can use es5-shim to polyfill Array.isArray; or add the following
# only implement if no native implementation is available
if (typeof Array.isArray === 'undefined') {
Array.isArray = function(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
}
};
If you use jQuery you can use jQuery.isArray(obj) or $.isArray(obj). If you use underscore you can use _.isArray(obj)
If you don't need to detect arrays created in different frames you can also just use instanceof
obj instanceof Array
Note: the arguments keyword that can be used to access the argument of a function isn't an Array, even though it (usually) behaves like one:
var func = function() {
console.log(arguments) // [1, 2, 3]
console.log(arguments.length) // 3
console.log(Array.isArray(arguments)) // false !!!
console.log(arguments.slice) // undefined (Array.prototype methods not available)
console.log([3,4,5].slice) // function slice() { [native code] }
}
func(1, 2, 3)
I noticed someone mentioned jQuery, but I didn't know there was an isArray() function. It turns out it was added in version 1.3.
jQuery implements it as Peter suggests:
isArray: function( obj ) {
return toString.call(obj) === "[object Array]";
},
Having put a lot of faith in jQuery already (especially their techniques for cross-browser compatibility) I will either upgrade to version 1.3 and use their function (providing that upgrading doesn’t cause too many problems) or use this suggested method directly in my code.
Many thanks for the suggestions.
This is an old question but having the same problem i found a very elegant solution that i want to share.
Adding a prototype to Array makes it very simple
Array.prototype.isArray = true;
Now once if you have an object you want to test to see if its an array all you need is to check for the new property
var box = doSomething();
if (box.isArray) {
// do something
}
isArray is only available if its an array
Via Crockford:
function typeOf(value) {
var s = typeof value;
if (s === 'object') {
if (value) {
if (value instanceof Array) {
s = 'array';
}
} else {
s = 'null';
}
}
return s;
}
The main failing Crockford mentions is an inability to correctly determine arrays that were created in a different context, e.g., window.
That page has a much more sophisticated version if this is insufficient.
If you're only dealing with EcmaScript 5 and above then you can use the built in Array.isArray function
e.g.,
Array.isArray([]) // true
Array.isArray("foo") // false
Array.isArray({}) // false
I personally like Peter's suggestion: https://stackoverflow.com/a/767499/414784 (for ECMAScript 3. For ECMAScript 5, use Array.isArray())
Comments on the post indicate, however, that if toString() is changed at all, that way of checking an array will fail. If you really want to be specific and make sure toString() has not been changed, and there are no problems with the objects class attribute ([object Array] is the class attribute of an object that is an array), then I recommend doing something like this:
//see if toString returns proper class attributes of objects that are arrays
//returns -1 if it fails test
//returns true if it passes test and it's an array
//returns false if it passes test and it's not an array
function is_array(o)
{
// make sure an array has a class attribute of [object Array]
var check_class = Object.prototype.toString.call([]);
if(check_class === '[object Array]')
{
// test passed, now check
return Object.prototype.toString.call(o) === '[object Array]';
}
else
{
// may want to change return value to something more desirable
return -1;
}
}
Note that in JavaScript The Definitive Guide 6th edition, 7.10, it says Array.isArray() is implemented using Object.prototype.toString.call() in ECMAScript 5. Also note that if you're going to worry about toString()'s implementation changing, you should also worry about every other built in method changing too. Why use push()? Someone can change it! Such an approach is silly. The above check is an offered solution to those worried about toString() changing, but I believe the check is unnecessary.
When I posted this question the version of JQuery that I was using didn't include an isArray function. If it had have I would have probably just used it trusting that implementation to be the best browser independant way to perform this particular type check.
Since JQuery now does offer this function, I would always use it...
$.isArray(obj);
(as of version 1.6.2) It is still implemented using comparisons on strings in the form
toString.call(obj) === "[object Array]"
Thought I would add another option for those who might already be using the Underscore.js library in their script. Underscore.js has an isArray() function (see http://underscorejs.org/#isArray).
_.isArray(object)
Returns true if object is an Array.
If you are using Angular, you can use the angular.isArray() function
var myArray = [];
angular.isArray(myArray); // returns true
var myObj = {};
angular.isArray(myObj); //returns false
http://docs.angularjs.org/api/ng/function/angular.isArray
In Crockford's JavaScript The Good Parts, there is a function to check if the given argument is an array:
var is_array = function (value) {
return value &&
typeof value === 'object' &&
typeof value.length === 'number' &&
typeof value.splice === 'function' &&
!(value.propertyIsEnumerable('length'));
};
He explains:
First, we ask if the value is truthy. We do this to reject null and other falsy values. Second, we ask if the typeof value is 'object'. This will be true for objects, arrays, and (weirdly) null. Third, we ask if the value has a length property that is a number. This will always be true for arrays, but usually not for objects. Fourth, we ask if the value contains a splice method. This again will be true for all arrays. Finally, we ask if the length property is enumerable (will length be produced by a for in loop?). That will be false for all arrays. This is the most reliable test for arrayness that I have found. It is unfortunate that it is so complicated.
The universal solution is below:
Object.prototype.toString.call(obj)=='[object Array]'
Starting from ECMAScript 5, a formal solution is :
Array.isArray(arr)
Also, for old JavaScript libs, you can find below solution although it's not accurate enough:
var is_array = function (value) {
return value &&
typeof value === 'object' &&
typeof value.length === 'number' &&
typeof value.splice === 'function' &&
!(value.propertyIsEnumerable('length'));
};
The solutions are from http://www.pixelstech.net/topic/85-How-to-check-whether-an-object-is-an-array-or-not-in-JavaScript
For those who code-golf, an unreliable test with fewest characters:
function isArray(a) {
return a.map;
}
This is commonly used when traversing/flattening a hierarchy:
function golf(a) {
return a.map?[].concat.apply([],a.map(golf)):a;
}
input: [1,2,[3,4,[5],6],[7,[8,[9]]]]
output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
code referred from https://github.com/miksago/Evan.js/blob/master/src/evan.js
var isArray = Array.isArray || function(obj) {
return !!(obj && obj.concat && obj.unshift && !obj.callee);};
I was using this line of code:
if (variable.push) {
// variable is array, since AMAIK only arrays have push() method.
}
I have created this little bit of code, which can return true types.
I am not sure about performance yet, but it's an attempt to properly identify the typeof.
https://github.com/valtido/better-typeOf also blogged a little about it here http://www.jqui.net/jquery/better-typeof-than-the-javascript-native-typeof/
it works, similar to the current typeof.
var user = [1,2,3]
typeOf(user); //[object Array]
It think it may need a bit of fine tuning, and take into account things, I have not come across or test it properly. so further improvements are welcomed, whether it's performance wise, or incorrectly re-porting of typeOf.
I think using myObj.constructor==Object and myArray.constructor==Array is the best way. Its almost 20x faster than using toString(). If you extend objects with your own constructors and want those creations to be considered "objects" as well than this doesn't work, but otherwise its way faster. typeof is just as fast as the constructor method but typeof []=='object' returns true which will often be undesirable. http://jsperf.com/constructor-vs-tostring
one thing to note is that null.constructor will throw an error so if you might be checking for null values you will have to first do if(testThing!==null){}
From w3schools:
function isArray(myArray) {
return myArray.constructor.toString().indexOf("Array") > -1;
}
I liked the Brian answer:
function is_array(o){
// make sure an array has a class attribute of [object Array]
var check_class = Object.prototype.toString.call([]);
if(check_class === '[object Array]') {
// test passed, now check
return Object.prototype.toString.call(o) === '[object Array]';
} else{
// may want to change return value to something more desirable
return -1;
}
}
but you could just do like this:
return Object.prototype.toString.call(o) === Object.prototype.toString.call([]);
I tried most of the solutions here. But none of them worked. Then I came up with a simple solution. Hope it will help someone & save their time.
if(variable.constructor != undefined && variable.constructor.length > 0) {
/// IT IS AN ARRAY
} else {
/// IT IS NOT AN ARRAY
}
Since the .length property is special for arrays in javascript you can simply say
obj.length === +obj.length // true if obj is an array
Underscorejs and several other libraries use this short and simple trick.
Something I just came up with:
if (item.length)
//This is an array
else
//not an array

How to find an object property is array or noT? [duplicate]

How do I check if a variable is an array in JavaScript?
if (variable.constructor == Array)
There are several ways of checking if an variable is an array or not. The best solution is the one you have chosen.
variable.constructor === Array
This is the fastest method on Chrome, and most likely all other browsers. All arrays are objects, so checking the constructor property is a fast process for JavaScript engines.
If you are having issues with finding out if an objects property is an array, you must first check if the property is there.
variable.prop && variable.prop.constructor === Array
Some other ways are:
Array.isArray(variable)
Update May 23, 2019 using Chrome 75, shout out to #AnduAndrici for having me revisit this with his question
This last one is, in my opinion the ugliest, and it is one of the slowest fastest. Running about 1/5 the speed as the first example. This guy is about 2-5% slower, but it's pretty hard to tell. Solid to use! Quite impressed by the outcome. Array.prototype, is actually an array. you can read more about it here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
variable instanceof Array
This method runs about 1/3 the speed as the first example. Still pretty solid, looks cleaner, if you're all about pretty code and not so much on performance. Note that checking for numbers does not work as variable instanceof Number always returns false. Update: instanceof now goes 2/3 the speed!
So yet another update
Object.prototype.toString.call(variable) === '[object Array]';
This guy is the slowest for trying to check for an Array. However, this is a one stop shop for any type you're looking for. However, since you're looking for an array, just use the fastest method above.
Also, I ran some test: http://jsperf.com/instanceof-array-vs-array-isarray/35 So have some fun and check it out.
Note: #EscapeNetscape has created another test as jsperf.com is down. http://jsben.ch/#/QgYAV I wanted to make sure the original link stay for whenever jsperf comes back online.
You could also use:
if (value instanceof Array) {
alert('value is Array!');
} else {
alert('Not an array');
}
This seems to me a pretty elegant solution, but to each his own.
Edit:
As of ES5 there is now also:
Array.isArray(value);
But this will break on older browsers, unless you are using polyfills (basically... IE8 or similar).
There are multiple solutions with all their own quirks. This page gives a good overview. One possible solution is:
function isArray(o) {
return Object.prototype.toString.call(o) === '[object Array]';
}
In modern browsers (and some legacy browsers), you can do
Array.isArray(obj)
(Supported by Chrome 5, Firefox 4.0, IE 9, Opera 10.5 and Safari 5)
If you need to support older versions of IE, you can use es5-shim to polyfill Array.isArray; or add the following
# only implement if no native implementation is available
if (typeof Array.isArray === 'undefined') {
Array.isArray = function(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
}
};
If you use jQuery you can use jQuery.isArray(obj) or $.isArray(obj). If you use underscore you can use _.isArray(obj)
If you don't need to detect arrays created in different frames you can also just use instanceof
obj instanceof Array
Note: the arguments keyword that can be used to access the argument of a function isn't an Array, even though it (usually) behaves like one:
var func = function() {
console.log(arguments) // [1, 2, 3]
console.log(arguments.length) // 3
console.log(Array.isArray(arguments)) // false !!!
console.log(arguments.slice) // undefined (Array.prototype methods not available)
console.log([3,4,5].slice) // function slice() { [native code] }
}
func(1, 2, 3)
I noticed someone mentioned jQuery, but I didn't know there was an isArray() function. It turns out it was added in version 1.3.
jQuery implements it as Peter suggests:
isArray: function( obj ) {
return toString.call(obj) === "[object Array]";
},
Having put a lot of faith in jQuery already (especially their techniques for cross-browser compatibility) I will either upgrade to version 1.3 and use their function (providing that upgrading doesn’t cause too many problems) or use this suggested method directly in my code.
Many thanks for the suggestions.
This is an old question but having the same problem i found a very elegant solution that i want to share.
Adding a prototype to Array makes it very simple
Array.prototype.isArray = true;
Now once if you have an object you want to test to see if its an array all you need is to check for the new property
var box = doSomething();
if (box.isArray) {
// do something
}
isArray is only available if its an array
Via Crockford:
function typeOf(value) {
var s = typeof value;
if (s === 'object') {
if (value) {
if (value instanceof Array) {
s = 'array';
}
} else {
s = 'null';
}
}
return s;
}
The main failing Crockford mentions is an inability to correctly determine arrays that were created in a different context, e.g., window.
That page has a much more sophisticated version if this is insufficient.
If you're only dealing with EcmaScript 5 and above then you can use the built in Array.isArray function
e.g.,
Array.isArray([]) // true
Array.isArray("foo") // false
Array.isArray({}) // false
I personally like Peter's suggestion: https://stackoverflow.com/a/767499/414784 (for ECMAScript 3. For ECMAScript 5, use Array.isArray())
Comments on the post indicate, however, that if toString() is changed at all, that way of checking an array will fail. If you really want to be specific and make sure toString() has not been changed, and there are no problems with the objects class attribute ([object Array] is the class attribute of an object that is an array), then I recommend doing something like this:
//see if toString returns proper class attributes of objects that are arrays
//returns -1 if it fails test
//returns true if it passes test and it's an array
//returns false if it passes test and it's not an array
function is_array(o)
{
// make sure an array has a class attribute of [object Array]
var check_class = Object.prototype.toString.call([]);
if(check_class === '[object Array]')
{
// test passed, now check
return Object.prototype.toString.call(o) === '[object Array]';
}
else
{
// may want to change return value to something more desirable
return -1;
}
}
Note that in JavaScript The Definitive Guide 6th edition, 7.10, it says Array.isArray() is implemented using Object.prototype.toString.call() in ECMAScript 5. Also note that if you're going to worry about toString()'s implementation changing, you should also worry about every other built in method changing too. Why use push()? Someone can change it! Such an approach is silly. The above check is an offered solution to those worried about toString() changing, but I believe the check is unnecessary.
When I posted this question the version of JQuery that I was using didn't include an isArray function. If it had have I would have probably just used it trusting that implementation to be the best browser independant way to perform this particular type check.
Since JQuery now does offer this function, I would always use it...
$.isArray(obj);
(as of version 1.6.2) It is still implemented using comparisons on strings in the form
toString.call(obj) === "[object Array]"
Thought I would add another option for those who might already be using the Underscore.js library in their script. Underscore.js has an isArray() function (see http://underscorejs.org/#isArray).
_.isArray(object)
Returns true if object is an Array.
If you are using Angular, you can use the angular.isArray() function
var myArray = [];
angular.isArray(myArray); // returns true
var myObj = {};
angular.isArray(myObj); //returns false
http://docs.angularjs.org/api/ng/function/angular.isArray
In Crockford's JavaScript The Good Parts, there is a function to check if the given argument is an array:
var is_array = function (value) {
return value &&
typeof value === 'object' &&
typeof value.length === 'number' &&
typeof value.splice === 'function' &&
!(value.propertyIsEnumerable('length'));
};
He explains:
First, we ask if the value is truthy. We do this to reject null and other falsy values. Second, we ask if the typeof value is 'object'. This will be true for objects, arrays, and (weirdly) null. Third, we ask if the value has a length property that is a number. This will always be true for arrays, but usually not for objects. Fourth, we ask if the value contains a splice method. This again will be true for all arrays. Finally, we ask if the length property is enumerable (will length be produced by a for in loop?). That will be false for all arrays. This is the most reliable test for arrayness that I have found. It is unfortunate that it is so complicated.
The universal solution is below:
Object.prototype.toString.call(obj)=='[object Array]'
Starting from ECMAScript 5, a formal solution is :
Array.isArray(arr)
Also, for old JavaScript libs, you can find below solution although it's not accurate enough:
var is_array = function (value) {
return value &&
typeof value === 'object' &&
typeof value.length === 'number' &&
typeof value.splice === 'function' &&
!(value.propertyIsEnumerable('length'));
};
The solutions are from http://www.pixelstech.net/topic/85-How-to-check-whether-an-object-is-an-array-or-not-in-JavaScript
For those who code-golf, an unreliable test with fewest characters:
function isArray(a) {
return a.map;
}
This is commonly used when traversing/flattening a hierarchy:
function golf(a) {
return a.map?[].concat.apply([],a.map(golf)):a;
}
input: [1,2,[3,4,[5],6],[7,[8,[9]]]]
output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
code referred from https://github.com/miksago/Evan.js/blob/master/src/evan.js
var isArray = Array.isArray || function(obj) {
return !!(obj && obj.concat && obj.unshift && !obj.callee);};
I was using this line of code:
if (variable.push) {
// variable is array, since AMAIK only arrays have push() method.
}
I have created this little bit of code, which can return true types.
I am not sure about performance yet, but it's an attempt to properly identify the typeof.
https://github.com/valtido/better-typeOf also blogged a little about it here http://www.jqui.net/jquery/better-typeof-than-the-javascript-native-typeof/
it works, similar to the current typeof.
var user = [1,2,3]
typeOf(user); //[object Array]
It think it may need a bit of fine tuning, and take into account things, I have not come across or test it properly. so further improvements are welcomed, whether it's performance wise, or incorrectly re-porting of typeOf.
I think using myObj.constructor==Object and myArray.constructor==Array is the best way. Its almost 20x faster than using toString(). If you extend objects with your own constructors and want those creations to be considered "objects" as well than this doesn't work, but otherwise its way faster. typeof is just as fast as the constructor method but typeof []=='object' returns true which will often be undesirable. http://jsperf.com/constructor-vs-tostring
one thing to note is that null.constructor will throw an error so if you might be checking for null values you will have to first do if(testThing!==null){}
From w3schools:
function isArray(myArray) {
return myArray.constructor.toString().indexOf("Array") > -1;
}
I liked the Brian answer:
function is_array(o){
// make sure an array has a class attribute of [object Array]
var check_class = Object.prototype.toString.call([]);
if(check_class === '[object Array]') {
// test passed, now check
return Object.prototype.toString.call(o) === '[object Array]';
} else{
// may want to change return value to something more desirable
return -1;
}
}
but you could just do like this:
return Object.prototype.toString.call(o) === Object.prototype.toString.call([]);
I tried most of the solutions here. But none of them worked. Then I came up with a simple solution. Hope it will help someone & save their time.
if(variable.constructor != undefined && variable.constructor.length > 0) {
/// IT IS AN ARRAY
} else {
/// IT IS NOT AN ARRAY
}
Since the .length property is special for arrays in javascript you can simply say
obj.length === +obj.length // true if obj is an array
Underscorejs and several other libraries use this short and simple trick.
Something I just came up with:
if (item.length)
//This is an array
else
//not an array

Which is the way to check an argument is an array and if not turn it into it in Javascript? [duplicate]

How do I check if a variable is an array in JavaScript?
if (variable.constructor == Array)
There are several ways of checking if an variable is an array or not. The best solution is the one you have chosen.
variable.constructor === Array
This is the fastest method on Chrome, and most likely all other browsers. All arrays are objects, so checking the constructor property is a fast process for JavaScript engines.
If you are having issues with finding out if an objects property is an array, you must first check if the property is there.
variable.prop && variable.prop.constructor === Array
Some other ways are:
Array.isArray(variable)
Update May 23, 2019 using Chrome 75, shout out to #AnduAndrici for having me revisit this with his question
This last one is, in my opinion the ugliest, and it is one of the slowest fastest. Running about 1/5 the speed as the first example. This guy is about 2-5% slower, but it's pretty hard to tell. Solid to use! Quite impressed by the outcome. Array.prototype, is actually an array. you can read more about it here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
variable instanceof Array
This method runs about 1/3 the speed as the first example. Still pretty solid, looks cleaner, if you're all about pretty code and not so much on performance. Note that checking for numbers does not work as variable instanceof Number always returns false. Update: instanceof now goes 2/3 the speed!
So yet another update
Object.prototype.toString.call(variable) === '[object Array]';
This guy is the slowest for trying to check for an Array. However, this is a one stop shop for any type you're looking for. However, since you're looking for an array, just use the fastest method above.
Also, I ran some test: http://jsperf.com/instanceof-array-vs-array-isarray/35 So have some fun and check it out.
Note: #EscapeNetscape has created another test as jsperf.com is down. http://jsben.ch/#/QgYAV I wanted to make sure the original link stay for whenever jsperf comes back online.
You could also use:
if (value instanceof Array) {
alert('value is Array!');
} else {
alert('Not an array');
}
This seems to me a pretty elegant solution, but to each his own.
Edit:
As of ES5 there is now also:
Array.isArray(value);
But this will break on older browsers, unless you are using polyfills (basically... IE8 or similar).
There are multiple solutions with all their own quirks. This page gives a good overview. One possible solution is:
function isArray(o) {
return Object.prototype.toString.call(o) === '[object Array]';
}
In modern browsers (and some legacy browsers), you can do
Array.isArray(obj)
(Supported by Chrome 5, Firefox 4.0, IE 9, Opera 10.5 and Safari 5)
If you need to support older versions of IE, you can use es5-shim to polyfill Array.isArray; or add the following
# only implement if no native implementation is available
if (typeof Array.isArray === 'undefined') {
Array.isArray = function(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
}
};
If you use jQuery you can use jQuery.isArray(obj) or $.isArray(obj). If you use underscore you can use _.isArray(obj)
If you don't need to detect arrays created in different frames you can also just use instanceof
obj instanceof Array
Note: the arguments keyword that can be used to access the argument of a function isn't an Array, even though it (usually) behaves like one:
var func = function() {
console.log(arguments) // [1, 2, 3]
console.log(arguments.length) // 3
console.log(Array.isArray(arguments)) // false !!!
console.log(arguments.slice) // undefined (Array.prototype methods not available)
console.log([3,4,5].slice) // function slice() { [native code] }
}
func(1, 2, 3)
I noticed someone mentioned jQuery, but I didn't know there was an isArray() function. It turns out it was added in version 1.3.
jQuery implements it as Peter suggests:
isArray: function( obj ) {
return toString.call(obj) === "[object Array]";
},
Having put a lot of faith in jQuery already (especially their techniques for cross-browser compatibility) I will either upgrade to version 1.3 and use their function (providing that upgrading doesn’t cause too many problems) or use this suggested method directly in my code.
Many thanks for the suggestions.
This is an old question but having the same problem i found a very elegant solution that i want to share.
Adding a prototype to Array makes it very simple
Array.prototype.isArray = true;
Now once if you have an object you want to test to see if its an array all you need is to check for the new property
var box = doSomething();
if (box.isArray) {
// do something
}
isArray is only available if its an array
Via Crockford:
function typeOf(value) {
var s = typeof value;
if (s === 'object') {
if (value) {
if (value instanceof Array) {
s = 'array';
}
} else {
s = 'null';
}
}
return s;
}
The main failing Crockford mentions is an inability to correctly determine arrays that were created in a different context, e.g., window.
That page has a much more sophisticated version if this is insufficient.
If you're only dealing with EcmaScript 5 and above then you can use the built in Array.isArray function
e.g.,
Array.isArray([]) // true
Array.isArray("foo") // false
Array.isArray({}) // false
I personally like Peter's suggestion: https://stackoverflow.com/a/767499/414784 (for ECMAScript 3. For ECMAScript 5, use Array.isArray())
Comments on the post indicate, however, that if toString() is changed at all, that way of checking an array will fail. If you really want to be specific and make sure toString() has not been changed, and there are no problems with the objects class attribute ([object Array] is the class attribute of an object that is an array), then I recommend doing something like this:
//see if toString returns proper class attributes of objects that are arrays
//returns -1 if it fails test
//returns true if it passes test and it's an array
//returns false if it passes test and it's not an array
function is_array(o)
{
// make sure an array has a class attribute of [object Array]
var check_class = Object.prototype.toString.call([]);
if(check_class === '[object Array]')
{
// test passed, now check
return Object.prototype.toString.call(o) === '[object Array]';
}
else
{
// may want to change return value to something more desirable
return -1;
}
}
Note that in JavaScript The Definitive Guide 6th edition, 7.10, it says Array.isArray() is implemented using Object.prototype.toString.call() in ECMAScript 5. Also note that if you're going to worry about toString()'s implementation changing, you should also worry about every other built in method changing too. Why use push()? Someone can change it! Such an approach is silly. The above check is an offered solution to those worried about toString() changing, but I believe the check is unnecessary.
When I posted this question the version of JQuery that I was using didn't include an isArray function. If it had have I would have probably just used it trusting that implementation to be the best browser independant way to perform this particular type check.
Since JQuery now does offer this function, I would always use it...
$.isArray(obj);
(as of version 1.6.2) It is still implemented using comparisons on strings in the form
toString.call(obj) === "[object Array]"
Thought I would add another option for those who might already be using the Underscore.js library in their script. Underscore.js has an isArray() function (see http://underscorejs.org/#isArray).
_.isArray(object)
Returns true if object is an Array.
If you are using Angular, you can use the angular.isArray() function
var myArray = [];
angular.isArray(myArray); // returns true
var myObj = {};
angular.isArray(myObj); //returns false
http://docs.angularjs.org/api/ng/function/angular.isArray
In Crockford's JavaScript The Good Parts, there is a function to check if the given argument is an array:
var is_array = function (value) {
return value &&
typeof value === 'object' &&
typeof value.length === 'number' &&
typeof value.splice === 'function' &&
!(value.propertyIsEnumerable('length'));
};
He explains:
First, we ask if the value is truthy. We do this to reject null and other falsy values. Second, we ask if the typeof value is 'object'. This will be true for objects, arrays, and (weirdly) null. Third, we ask if the value has a length property that is a number. This will always be true for arrays, but usually not for objects. Fourth, we ask if the value contains a splice method. This again will be true for all arrays. Finally, we ask if the length property is enumerable (will length be produced by a for in loop?). That will be false for all arrays. This is the most reliable test for arrayness that I have found. It is unfortunate that it is so complicated.
The universal solution is below:
Object.prototype.toString.call(obj)=='[object Array]'
Starting from ECMAScript 5, a formal solution is :
Array.isArray(arr)
Also, for old JavaScript libs, you can find below solution although it's not accurate enough:
var is_array = function (value) {
return value &&
typeof value === 'object' &&
typeof value.length === 'number' &&
typeof value.splice === 'function' &&
!(value.propertyIsEnumerable('length'));
};
The solutions are from http://www.pixelstech.net/topic/85-How-to-check-whether-an-object-is-an-array-or-not-in-JavaScript
For those who code-golf, an unreliable test with fewest characters:
function isArray(a) {
return a.map;
}
This is commonly used when traversing/flattening a hierarchy:
function golf(a) {
return a.map?[].concat.apply([],a.map(golf)):a;
}
input: [1,2,[3,4,[5],6],[7,[8,[9]]]]
output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
code referred from https://github.com/miksago/Evan.js/blob/master/src/evan.js
var isArray = Array.isArray || function(obj) {
return !!(obj && obj.concat && obj.unshift && !obj.callee);};
I was using this line of code:
if (variable.push) {
// variable is array, since AMAIK only arrays have push() method.
}
I have created this little bit of code, which can return true types.
I am not sure about performance yet, but it's an attempt to properly identify the typeof.
https://github.com/valtido/better-typeOf also blogged a little about it here http://www.jqui.net/jquery/better-typeof-than-the-javascript-native-typeof/
it works, similar to the current typeof.
var user = [1,2,3]
typeOf(user); //[object Array]
It think it may need a bit of fine tuning, and take into account things, I have not come across or test it properly. so further improvements are welcomed, whether it's performance wise, or incorrectly re-porting of typeOf.
I think using myObj.constructor==Object and myArray.constructor==Array is the best way. Its almost 20x faster than using toString(). If you extend objects with your own constructors and want those creations to be considered "objects" as well than this doesn't work, but otherwise its way faster. typeof is just as fast as the constructor method but typeof []=='object' returns true which will often be undesirable. http://jsperf.com/constructor-vs-tostring
one thing to note is that null.constructor will throw an error so if you might be checking for null values you will have to first do if(testThing!==null){}
From w3schools:
function isArray(myArray) {
return myArray.constructor.toString().indexOf("Array") > -1;
}
I liked the Brian answer:
function is_array(o){
// make sure an array has a class attribute of [object Array]
var check_class = Object.prototype.toString.call([]);
if(check_class === '[object Array]') {
// test passed, now check
return Object.prototype.toString.call(o) === '[object Array]';
} else{
// may want to change return value to something more desirable
return -1;
}
}
but you could just do like this:
return Object.prototype.toString.call(o) === Object.prototype.toString.call([]);
I tried most of the solutions here. But none of them worked. Then I came up with a simple solution. Hope it will help someone & save their time.
if(variable.constructor != undefined && variable.constructor.length > 0) {
/// IT IS AN ARRAY
} else {
/// IT IS NOT AN ARRAY
}
Since the .length property is special for arrays in javascript you can simply say
obj.length === +obj.length // true if obj is an array
Underscorejs and several other libraries use this short and simple trick.
Something I just came up with:
if (item.length)
//This is an array
else
//not an array

Using 'in' when the object may be a string

I was looking up how to check if a variable in JavaScript is an array, but then as the SO page was loading, I thought of a solution to the problem. Looking through the answers, I found that none of them had thought of this simple answer: Just check for the methods we need to use on the array, so that it still works for any user defined types that implement the same methods. Being the helpful person I am, I thought I'd submit my answer for future people trying to solve the same problem..But after testing it, I found it does not work.
function print(object) {
if ('map' in object) { // If the object implements map, treat it like an array
object.map(function(current) {
console.log(current);
});
} else { // Otherwise, treat it as a string
console.log(object);
}
}
Now, this works fine when I call it with an array, but if I use a string it fails. Since strings are objects in javascript, why shouldn't the 'in' keyword work for them? Is there any way to implement this that is as simple as what it currently is?
You can access the property and test its type:
if (object != null && typeof object.map === 'function')
object.map(...);
// ...
Since strings are objects in javascript, why shouldn't the 'in' keyword work for them?
Not quite. There is a difference between a primitive string value and a String instance object.
typeof "foo"; // "string"
typeof new String(); // "object"
Primitive values don't have properties themselves, which is why the in operator throws an Error when used on them. They will, however, be temporarily boxed into Objects by property accessors:
var a = "foo";
a.bar = 'bar'; // no error, but...
console.log(a.bar); // undefined
String.prototype.baz = function () {
return this + this;
};
console.log(a.baz()); // "foofoo"
I suppose you could do something like this:
var y = function (o) {
if (typeof o != "string" && "map" in o)
console.log("not a string"); //your code here
else
console.log("It's a string!"); //your code here
}
I tested this with var x = "hello" and it worked. Because && short circuits in JavaScript, it will stop at typeof o != "string", which is good, since "map" in o fails for strings. Note the intentional use of lowercase, which is for primitives; Strings are objects. I'm not exactly sure if this is what you were aiming for.

When to check for undefined and when to check for null

[Bounty Edit]
I'm looking for a good explanation when you should set/use null or undefined and where you need to check for it. Basically what are common practices for these two and is really possible to treat them separately in generic maintainable codee?
When can I safely check for === null, safely check for === undefined and when do I need to check for both with == null
When should you use the keyword undefined and when should one use the keyword null
I have various checks in the format of
if (someObj == null) or if (someObj != null) which check for both null and undefined. I would like to change all these to either === undefined or === null but I'm not sure how to guarantee that it will only ever be one of the two but not both.
Where should you use checks for null and where should you use checks for undefined
A concrete example:
var List = []; // ordered list contains data at odd indexes.
var getObject = function(id) {
for (var i = 0; i < List.length; i++) {
if (List[i] == null) continue;
if (id === List[i].getId()) {
return List[i];
}
}
return null;
}
var deleteObject = function(id) {
var index = getIndex(id) // pretty obvouis function
// List[index] = null; // should I set it to null?
delete List[index]; // should I set it to undefined?
}
This is just one example of where I can use both null or undefined and I don't know which is correct.
Are there any cases where you must check for both null and undefined because you have no choice?
Functions implicitly return undefined. Undefined keys in arrays are undefined. Undefined attributes in objects are undefined.
function foo () {
};
var bar = [];
var baz = {};
//foo() === undefined && bar[100] === undefined && baz.something === undefined
document.getElementById returns null if no elements are found.
var el = document.getElementById("foo");
// el === null || el instanceof HTMLElement
You should never have to check for undefined or null (unless you're aggregating data from both a source that may return null, and a source which may return undefined).
I recommend you avoid null; use undefined.
Some DOM methods return null. All properties of an object that have not been set return undefined when you attempt to access them, including properties of an Array. A function with no return statement implicitly returns undefined.
I would suggest making sure you know exactly what values are possible for the variable or property you're testing and testing for these values explicitly and with confidence. For testing null, use foo === null. For testing for undefined, I would recommend using typeof foo == "undefined" in most situations, because undefined (unlike null) is not a reserved word and is instead a simple property of the global object that may be altered, and also for other reasons I wrote about recently here: variable === undefined vs. typeof variable === "undefined"
The difference between null and undefined is that null is itself a value and has to be assigned. It's not the default. A brand new variable with no value assigned to it is undefined.
var x;
// value undefined - NOT null.
x = null;
// value null - NOT undefined.
I think it's interesting to note that, when Windows was first written, it didn't do a lot of checks for invalid/NULL pointers. Afterall, no programmer would be dumb enough to pass NULL where a valid string was needed. And testing for NULL just makes the code larger and slower.
The result was that many UAEs were due to errors in client programs, but all the heat went to Microsoft. Since then, Microsoft has changed Windows to pretty much check every argument for NULL.
I think the lesson is that, unless you are really sure an argument will always be valid, it's probably worth verifying that it is. Of course, Windows is used by a lot of programmers while your function may only be used by you. So that certainly factors in regarding how likely an invalid argument is.
In languages like C and C++, you can use ASSERTs and I use them ALL the time when using these languages. These are statements that verify certain conditions that you never expect to happen. During debugging, you can test that, in fact, they never do. Then when you do a release build these statements are not included in the compiled code. In some ways, this seems like the best of both worlds to me.
If you call a function with no explicit return then it implicitly returns undefined. So if I have a function that needs to say that it did its task and there is nothing result, e.g. a XMLHTTPRequest that returned nothing when you normally expect that there would be something (like a database call), then I would explicitly return null.
Undefined is different from null when using !== but not when using the weaker != because JavaScript does some implicit casting in this case.
The main difference between null and undefined is that undefined can also mean something which has not been assigned to.
undefined false
(SomeObject.foo) false false
(SomeObject.foo != null) false true
(SomeObject.foo !== null) true true
(SomeObject.foo != false) true false
(SomeObject.foo !== false) true false
This is taken from this weblog
The problem is that you claim to see the difference, but you don't. Take your example. It should really be:
var List = []; // ordered list contains data at odd indexes.
var getObject = function(id) {
for (var i = 1; i < List.length; i+=2) {
if (id === List[i].getId()) {
return List[i];
}
}
// returns undefined by default
}
Your algorithm is flawed because you check even indexes (even though you know there's nothing there), and you also misuse null as a return value.
These kind of functions should really return undefined because it means: there's no such data
And there you are in the heart of the problem. If you don't fully understand null and undefined and may use them wrongly sometimes, how can you be so sure that others will use it correctly? You can't.
Then there are Host objects with their nasty behavior, if you ask me, you better off checking for both. It doesn't hurt, in fact, it saves you some headaches dealing with third party code, or the aformentioned non-native objects.
Except for these two cases, in your own code, you can do what #bobince said:
Keep undefined as a special value for signalling when other languages might throw an exception instead.
When to set/use them...
Note that a method without a return statement returns undefined, you shouldn't force this as an expected response, if you use it in a method that should always return a value, then it should represent an error state internally.
Use null for an intentional or non-match response.
As for how/when to check...
undefined, null, 0, an empty string, NaN and false will be FALSE via coercion. These are known as "falsy" values... everything else is true.
Your best bet is coercion then testing for valid exception values...
var something; //undefined
something = !!something; //something coerced into a boolean
//true if false, null, NaN or undefined
function isFalsish(value) {
return (!value && value !== "" && value !== 0);
}
//get number or default
function getNumber(val, defaultVal) {
defaultVal = isFalsish(defaultVal) ? 0 : defaultVal;
return (isFalsish(val) || isNaN(val)) ? defaultVal : +val;
}
Numeric testing is the real bugger, since true, false and null can be coerced into a number, and 0 coerces to false.
I would treat them as 2 completely different values, and check for the one you know might occur.
If you're checking to see if something has been given a value yet, check against undefined.
If you're checking to see if the value is 'nothing,' check against 'null'
A slightly contrived example:
Say you have a series of ajax requests, and you're morally opposed to using callbacks so you have a timeout running that checks for their completion.
Your check would look something like this:
if (result !== undefined){
//The ajax requests have completed
doOnCompleteStuff();
if (result !== null){
//There is actually data to process
doSomething(result);
}
}
tldr; They are two different values, undefined means no value has been given, null means a value has been given, but the value is 'nothing'.

Categories