Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

141
Views
Should I be explicitly checking if the first statement in my if condition is null?

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'; 
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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'
  }
about 4 years ago · Juan Pablo Isaza Report

0

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'
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!