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.

Matt Ferderer

Software engineer who spends his time learning about building teams, project management, software architecture, C#, .NET Core, Blazor, JavaScript, TypeScript, Azure, user experience, web security, and performance.