Search code examples
javascriptstringundefined

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?


Solution

  • 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>         
        `;
    });