Home > other >  Should I be explicitly checking if the first statement in my if condition is null?
Should I be explicitly checking if the first statement in my if condition is null?

Time:12-17

I'm trying to see what's wrong with the if statement below. Can any of you enlighten me on where there might be a case that this line could throw an error? Do I need to explicitly check if the element is null or undefined? Here's the code:

  const firstElement = document.querySelector('.large-image > a > img');
  const secondElement = document.querySelector('.slides > li');
  
  // This is the line I'm referring too
  if ((firstElement && firstElement.offsetWidth > 0) && firstElement.getAttribute('src') == secondElement.firstChild.getAttribute('src')) 
  return 'ELEMENT'; 
}

CodePudding user response:

First let's reformat that line so it's readable:

  // This is the line I'm referring too
  if (
    firstElement &&
    firstElement.offsetWidth > 0 &&
    firstElement.getAttribute('src') == secondElement.firstChild.getAttribute('src')
  ) {
    return 'ELEMENT'
  }

If the element at .slides > li is not found on the document, then secondElement will be undefined.

And then when it gets to secondElement.firstChild it will crash because firstElement cannot be accessed on undefined.

So if either element might not exist on the page when this code is run, then you must check that both elements exists before accessing them.

Maybe something like:

  if (
    firstElement &&
    secondElement &&
    secondElement.firstChild && // couldn't hurt ¯\_(ツ)_/¯
    firstElement.offsetWidth > 0 &&
    firstElement.getAttribute('src') == secondElement.firstChild.getAttribute('src')
  ) {
    return 'ELEMENT'
  }

CodePudding user response:

You can also use Optional chaining (?.) to accomplish the same task by writing less code.

Optional Chaining Operator (?.) - MDN Documentation

The optional chaining operator (?.) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.

if (
  firstElement?.offsetWidth > 0 &&
  firstElement?.getAttribute('src') === secondElement?.firstChild?.getAttribute('src')
) {
  return 'ELEMENT'
}
  • Related