How to Use Nested String Interpolation in JavaScript

Feature thumb snip20170718 8

There are many times where you need to perform actions inside of large strings. Examples might be:

Performing a loop Implementing conditionals

Let's examine a basic example. Let's imagine that we have a JavaScript object:

I want to render this on a website, however the food attribute is optional, so I can't expect that it will always be available. So if I run code like this:

This will work and show the object properties:

But if I remove the optional 'food' attribute, the output will be:

This is because the food attribute isn't in the object any longer. Ideally the Food line item shouldn't even be displayed if the attribute doesn't exist. We can accomplish this behavior by adding a nested ternary operator inside of the JavaScript string literal, so the updated code will look like this:

Now if you update the page you'll see that the Food line item has disappeared, and if you add the food attribute back into the object it will show up again.

In earlier versions of JavaScript, this would have been very tedious. However in more modern JavaScript, the string literal syntax makes it much easier to manipulate string based data.