Reputation:
different from obj != null;
I know that obj != null
will detect anything that is allowed to have properties on it as null and undefined are the only two values which can not have properties.
How does this differ from
Object(obj) === obj;
Upvotes: 8
Views: 1062
Reputation: 123513
Object(obj) === obj
tests whether obj
is an object or a primitive, failing also for strings, etc.
console.log(Object('foo') === 'foo'); // false
console.log(Object(true) === true); // false
console.log(Object(null) === null); // false
var obj = {};
console.log(Object(obj) === obj); // true
It's useful for determining if the value can be given and remember an assigned property.
While null
and undefined
outright error when attempting to use properties, which is why obj != null
is still useful, no primitive values are able to hold onto properties.
var pri = 'foo';
pri.foo = 'bar'; // no error, but still...
console.log(pri.foo); // undefined
var box = Object(pri);
box.foo = 'bar';
console.log(box.foo); // 'bar'
Reference:
When obj
is null
or undefined
, Object(obj)
returns a new Object()
:
1) If value is
null
,undefined
or not supplied, create and return a new Object object exactly as if the standard built-in Object constructor had been called with the same arguments (15.2.2.1).
And, primitive booleans, strings, and numbers are boxed into their object types via ToObject()
, which are not equal to their primitive equivalents:
2) Return ToObject(value).
console.log(typeof 'foo' === 'string'); // true
console.log(typeof Object('foo') === 'object'); // true
console.log('foo' instanceof String); // false
console.log(Object('foo') instanceof String); // true
Upvotes: 7
Reputation: 241
Identity (===. !==)
These operators behave identically to the equality operators except no type conversion is done, and the types must be the same to be considered equal.
http://www.c-point.com/javascript_tutorial/jsgrpComparison.htm
Nice Stack overflow link Which equals operator (== vs ===) should be used in JavaScript comparisons?
Hope it helps
Upvotes: -3