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

258
Views
How to replace 'undefined' with an empty string in JavaScript

I'm pulling in product data from an API. For more than half of the products, the product year doesn't exist. Instead, it returns as undefined.

Instead of displaying the word undefined, I'd like to replace it with an empty string.

Here's my code below:

product.photos.map(() => {
    let year = "";
    if (product.year === undefined) {
        year = product.year;
    }
    // Then output the data
    output += `
            <div class="card">
              <img class="img-fluid" src=${product.photos[0].text} alt=${product.model} />
              <h3>${product.year} ${product.manufacturer} ${product.model}</h3>
              <p>${product.hours} hours</p>
              <a href='https://used.battlefieldequipment.ca/en/${product["group-code"]}/${product["serial-number"]}' class="btn btn-primary">View Details</a>
            </div>         
        `;
});

Doesn't seem to work. How would I go about correcting this?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

I think you should use

product.year = product.year ?? ''

instead of

let year = "";
if (product.year === undefined) {
  year = product.year;
}
about 4 years ago · Juan Pablo Isaza Report

0

You could use the nullish coalescing operator inline in your output string.

product.photos.map(() => {
    // output the data
    output += `
            <div class="card">
              <img class="img-fluid" src=${product.photos[0].text} alt=${product.model} />
              <h3>${product.year ?? ''} ${product.manufacturer} ${product.model}</h3>
              <p>${product.hours} hours</p>
              <a href='https://used.battlefieldequipment.ca/en/${product["group-code"]}/${product["serial-number"]}' class="btn btn-primary">View Details</a>
            </div>         
    `;
});
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!