Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 751
infused Avatar asked Mar 09 '26 10:03

infused


2 Answers

I think you should use

product.year = product.year ?? ''

instead of

let year = "";
if (product.year === undefined) {
  year = product.year;
}
like image 122
Bulent Avatar answered Mar 11 '26 22:03

Bulent


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>         
    `;
});
like image 30
nullromo Avatar answered Mar 11 '26 23:03

nullromo