1

My friend told me that this code "is used to check the survival of Javascript object":

Example: I have 2 objects and each one has 2 property called 'a' and 'b'

var obj1 = {a:0,b:0}
var obj2 = {a:3,b:4}

With the obj1 with the value of all property is 0 and 'obj2' have child property's value is an integer and I make the 'obj1' to be the first operator of the checking expression then I have got result is "failed".

if((obj1.a && obj1.b)&& obj2){
    document.write("success")
}else{
   document.write("failed")
}

But otherwise if I make obj1 is the second operator then I have got result is "success" like this:

if((obj2.a && obj2.b)&& obj1){
    document.write("success")
}else{
document.write("failed")
}

Can anyone explain to me why?

var obj1 = {a:0,b:0}
var obj2 = {a:3,b:4}


if((obj1.a && obj1.b)&& obj2){
   document.write("success")
}else{
  document.write("failed")
}

document.write("<br><br>")

if((obj2.a && obj2.b)&& obj1){
    document.write("success")
}else{
    document.write("failed")
}
John Kugelman
  • 307,513
  • 65
  • 473
  • 519
IRIS
  • 11
  • 2

2 Answers2

4

Can anyone explain to me why ?

You're observing the truthy and falsy nature of JavaScript's type-system.

The if expression in this:

var obj1 = { a: 0, b: 0 };
var obj2 = { a: 3, b: 4 };

if( ( obj1.a && obj1.b ) && obj2 ) {

is:

( obj1.a && obj1.b ) && obj2

...is effectively this:

( 0 && 0 ) && aNonNullObject

==

( false && false ) && true

==

( false ) && true

==

false

Whereas the other example:

if( ( obj2.a && obj2.b ) && obj1 ) {

...is:

( 3 && 4 ) && aNonNullObject

==

( true && true ) && true

==

( true ) && true

==

true

  • This is because 0, null, undefined, and empty-strings "" are falsy.
  • Whereas non-zero numbers, non-null objects, and non-empty-strings are truthy.

Also, don't use document.write.


"is used to check the survival of Javascript object"

"Survival" is not a term used in JavaScript - or programming in general, so I'd wager that your friend is not an expert at JavaScript programming - I assume you got into the habit of using document.write from them too, so I'll advise you to not be uncritical in response to anything they say.

("Object lifetime" and "lifespan" are terms that are used in programming, but they are unrelated to the question you're asking).

Dai
  • 110,988
  • 21
  • 188
  • 277
-1

use hasOwnProperty

var obj1 = { a: 0, b: 0 };
var obj2 = { a: 3, b: 4 };

if (obj1.hasOwnProperty('a') && obj1.hasOwnProperty('b') && obj2) {
  document.write("success"); // success
} else {
  document.write("failed");
}
januw a
  • 1,111
  • 2
  • 8
  • 23