Using Ternary Operators in ES6 String Templates

The new ES6 version of JavaScript introduced Template Strings which allow for improved readability of code when working with multiple line strings.

This allows us to avoid the following syntax:

//Common method
let foo = '<table>' +
	'<tr>' +
		'<td>Tables are a pain</td>' +
	'</tr>' +
//Alternate equally painful & ugly method
let foo = '<table> \
	<tr> \
		<td>Tables are a pain</td> \
	</tr> \

Instead we can now use the backtick character to create a string template. We can also include variables by wrapping them in ${}.

let enjoyment = 'not so bad';
let foo = `<table>
		<td>Tables are ${enjoyment}</td>

We can even take this farther and use a ternary operator to do an if/else statement, call a function and solve some math.

let displayAverages = true;
let totalSales = 500;
let sales = [50, 200, 125, 75, 25, 10, 15];
let tableTemplate = `<table id="sales">
		${displayAverages ? '<th>Averages</th>' : ''}
		${displayAverages ? `<td>${Math.round(totalSales/sales.length)}</td>` : ''}

Try it out for yourself on Plunker.

One Last Thing...

If you have a question or see a mistake, please comment below.

If you found this post helpful, please share it with others. It's the best thanks I can ask for & it gives me momentum to keep writing!

Matt Ferderer
Software Developer focused on making great user experiences. I enjoy learning, sharing & helping others make amazing things.
Let's Connect