8

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;

  • The result is not really the same. Take, for instance, a string or number primitive: it is != null but its object boxed counterpart is not === the primitive form. – Fabrício Matté Jun 27 '14 at 21:27

2 Answers2

7

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
Community
  • 1
  • 1
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
-3

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

Community
  • 1
  • 1
Kris
  • 251
  • 1
  • 8
  • 2
    I don't see how this answers the question. This is not just about != and !==, rather it is `x != null` and `Object(x) === x` – Fabrício Matté Jun 27 '14 at 21:22
  • First link gives the basic JS operator meaning and second link (SO) answers explains much better. Those two links gave me convincing answer to the problem. – Kris Jun 27 '14 at 21:30