3

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?

2
  • you have your assignment reversed Commented Sep 2, 2021 at 18:25
  • 1
    I think you meant to do if (product.year !== undefined) { (negating the expression). Alternative, you could use the 'falsy' mechanics of javascript to default to an empty string: let year = product.year || ""; Commented Sep 2, 2021 at 18:27

2 Answers 2

5

I think you should use

product.year = product.year ?? ''

instead of

let year = "";
if (product.year === undefined) {
  year = product.year;
}
Sign up to request clarification or add additional context in comments.

1 Comment

If product is a reference to an object somewhere else, then setting product.year = ... will change the underlying object, so be careful that this is not an unintended externality.
3

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

1 Comment

Thank you!! Never knew about this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.