Template literals - in JavaScript that provide a way to make string values dynamic. They are defined using backticks (`) instead of single (') or double (") quotes. With template literals/ template strings, variables can be used in strings. 1. String Interpolation Template literals allow you to embed variables inside a string using ${}
. For Example: [code lang="js"] const name = "Eugene"; console.log(`Hello, ${name}, how are you?`); // Output: Hello, Eugene, how are you?. [/code] Template literals allow you to leverage expressions inside a string using ${}
. This is especially useful when creating associating CSS classes, as shown below (Tailwind CSS): [code] <p className={`text-lg ${color == 'green' ? 'bg-green-500' : 'bg-red-500'}`}> Template literal [/code] Or when calling an API endpoints: [code] const response = await fetch(`http://localhost:3000/api/${recordTypeName}`, { method: 'PATCH', body: JSON.stringify(record), headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${user.token}` } }); [/code] 2. Multiline Strings With Template Literals, you can have a string that spans across multiple lines. Attempting to do the below with single or multi quotes would require string concatenation. [code] const message = `This is a string that spans multiple lines in JS.`; [/code]
Template literals (Template strings). How to use Dynamic String values in your code!

Written by:
Eugene Yeboah • April 28, 2023
