Back to subject
JavaScript/Strings & Template Literals

Build a Dynamic Sentence

Practical lesson

Let's read a template literal that combines plain text, a variable, and a method call, all in one string.

const name = "sara"; stores lowercase text on purpose, to make the next step visible.

Inside the template literal, ${name.toUpperCase()} does two things: first it calls .toUpperCase() on name, converting "sara" to "SARA", and the result of that call is what actually gets inserted into the string not the original name variable.

${name.length} inserts the number of characters in name importantly, .length is checked on the original name ("sara", 4 characters), not on the uppercase version, since toUpperCase() wasn't applied to that particular expression.

The final output reads "Hello, SARA! Your name has 4 letters." notice how ${...} can hold more than just a plain variable; any valid JavaScript expression works inside it, including method calls like this one.

Try it yourself
Code

Starter example

Code
<script>
  const name = "sara";
  const greeting = `Hello, ${name.toUpperCase()}! Your name has ${name.length} letters.`;
  document.body.innerHTML = `<p>${greeting}</p>`;
</script>
Live preview