EN
JavaScript - how to check if value is object?
14 points
The first important thing is what is primitive type in JavaScript?
Primitive type literals:
0
,1
,2
,-4
,NaN
,+Infinity
,-Infinity
, etc.'abc'
,''
, etc.true
/false
undefined
null
- special case, but we treat it as not defined object too
Everything else is object type!
In the below code shows how to check if value is object.
xxxxxxxxxx
1
function isObject(value) {
2
return value === Object(value);
3
}
4
5
6
// Usage example:
7
8
console.log( isObject(null) ); // false
9
console.log( isObject(undefined) ); // false
10
console.log( isObject(false) ); // false
11
console.log( isObject(true) ); // false
12
console.log( isObject(0) ); // false
13
console.log( isObject(1) ); // false
14
console.log( isObject(NaN) ); // false
15
console.log( isObject(+Infinity) ); // false
16
console.log( isObject('') ); // false
17
18
console.log( isObject([ ]) ); // true
19
console.log( isObject({ }) ); // true
20
console.log( isObject(function(){ }) ); // true
21
console.log( isObject(new Number(1)) ); // true
22
console.log( isObject(Object.prototype) ); // true
23
console.log( isObject(Object.create(null)) ); // true
xxxxxxxxxx
1
function isObject(value) {
2
if (value == null) { // null or undefined
3
return false;
4
}
5
var type = typeof value;
6
return type === 'function' || type === 'object';
7
}
8
9
10
// Usage example:
11
12
console.log( isObject(null) ); // false
13
console.log( isObject(undefined) ); // false
14
console.log( isObject(false) ); // false
15
console.log( isObject(true) ); // false
16
console.log( isObject(0) ); // false
17
console.log( isObject(1) ); // false
18
console.log( isObject(NaN) ); // false
19
console.log( isObject(+Infinity) ); // false
20
console.log( isObject('') ); // false
21
22
console.log( isObject([ ]) ); // true
23
console.log( isObject({ }) ); // true
24
console.log( isObject(function(){ }) ); // true
25
console.log( isObject(new Number(1)) ); // true
26
console.log( isObject(Object.prototype) ); // true
27
console.log( isObject(Object.create(null)) ); // true