How to skip the second part (JavaScript if statement) if the first part is false

I have this code:

  if (window.content.document.getElementById("error-msg") != null )
  {
    if (window.content.document.getElementById("error-msg").offsetParent !== null) 
    {
...
    }
  }

      

Can it be written in a single if statement?

I've tried the following ...

if ( (window.content.document.getElementById("error-msg") != null) || (window.content.document.getElementById("error-msg").offsetParent !== null) ) {}

      

But that didn't work and throws an error:

TypeError: window.content.document.getElementById (...) null

+3


source to share


2 answers


A common idiom is to use an operator &&

like this

var errorMsg = window.content.document.getElementById("error-msg");

if (errorMsg && errorMsg.offsetParent) {
    ...
}

      

Here JavaScript will evaluate first errorMsg

, and if it's Truthy then it will evaluate the part errorMsg.offsetParent

. The condition will be met only if both expressions in &&

are Truthy.

Note. ... Truthy's evaluation will return false

if the expression being tested 0

, false

etc. (see list of Falsy values here ). So, if you want to check if they are not null

, just write it explicitly like this

if (errorMsg !== null && errorMsg.offsetParent !== null) {
    ...
}

      




On the other hand, the operator ||

will evaluate the second operator only if the first expression is Falsy. In your case, if

(window.content.document.getElementById("error-msg") != null) 

      

is true

, it means it getElementById("error-msg")

returns null

. Since the first expression evaluates to Truthy, it evaluates to another expression and effectively tries to check

null.offsetParent !== null

      

This is why it fails.

+8


source


Maybe you want to use &&



if (a != null && b != null) {
    // Do something.
}

      

+3


source







All Articles