JavaScript does not have Python-style f-strings. Its closest equivalent is a template literal: write the string between backticks and put expressions inside ${...}, as in `Hello, ${name}!`. Template literals also support multiline text and a few features beyond simple interpolation.
What a JavaScript f-string means
Python programmers use an f-string prefix, such as f'Hello, {name}!', to insert values into a string. JavaScript has no f prefix or matching brace-only syntax. Instead, template literals provide the same everyday capability: they combine ordinary text with evaluated JavaScript expressions.
Template literals were introduced in ECMAScript 2015, also called ES6. They are a standard part of modern JavaScript and work in current mainstream browsers and Node.js versions. A template literal is identified by its backtick delimiters (`), rather than the single or double quotation marks used for ordinary string literals.
For example, suppose name contains 'Mina'. The template literal `Hello, ${name}!` produces Hello, Mina!. The characters outside the placeholder remain literal text; the expression between ${ and } is evaluated and converted into part of the resulting string.
Basic template literal syntax
Use a backtick at the beginning and end of the string, then wrap each value or expression in ${...}. The braces mark where the JavaScript expression begins and ends; they are not printed as part of the result.
const firstName = 'Mina';
const itemCount = 3;
const message = `Hi, ${firstName}. You have ${itemCount} messages.`;
console.log(message); // Hi, Mina. You have 3 messages.
Any valid expression can go inside a placeholder, not just a variable name. You can add values, call functions, or read object properties. Keep the expression inside the braces valid JavaScript, and use parentheses when they make a complicated expression easier to follow.
const price = 12;
const quantity = 4;
const summary = `Total: $${price * quantity}`;
console.log(summary); // Total: $48
JavaScript evaluates each placeholder when it evaluates the template literal. That means a function call inside one may run at that point. If the same function call appears twice, it runs twice; a template literal does not automatically save or reuse its result.
Expressions, values, and formatting
Interpolation converts the result of an expression to a string. Numbers, booleans, null, and undefined therefore appear as text when inserted. For instance, `Ready: ${true}` becomes Ready: true, and `Value: ${null}` becomes Value: null.
Objects may not turn into the display text you expect. A plain object commonly becomes [object Object], because that is its default string representation. Select the property you want, or explicitly serialize the object when JSON text is appropriate:
const user = { name: 'Mina', role: 'editor' };
const label = `User: ${user.name}`;
const json = `Data: ${JSON.stringify(user)}`;
Template literals do not provide Python-style format specifications such as a built-in instruction to show two decimal places. Apply JavaScript formatting before interpolation. For example, a number can be formatted with toFixed(2): `Price: $${price.toFixed(2)}`. For locale-sensitive display, use Intl.NumberFormat and interpolate its formatted result. Pick formatting based on the type and purpose of the value rather than assuming the template will format it automatically.
Expressions can also use conditional logic. A short conditional expression works well for a small variation, such as `Status: ${isOnline ? 'online' : 'offline'}`. For complex decisions, calculate the value in a separate statement first. That often makes the template easier to read and gives you a convenient place to test the logic.
Multiline strings and escaping
Unlike ordinary single- or double-quoted JavaScript strings, template literals can contain actual line breaks. The line breaks and indentation between the backticks become part of the resulting string. This is useful for short messages, markup-like text, or query text, but it can also introduce unwanted spaces if the source code is indented.
const message = `Hello, ${firstName}.
Your order is ready.`;
That example contains a newline between the two sentences. If you want one line instead, write the string on one line or join pieces explicitly. A backslash at the end of a source line can continue a template without adding a line break, but this can be difficult to see and maintain, so use it only when the behavior is clear.
To include a literal backtick inside the string, escape it with a backslash: `Use \`backticks\` here`. To show the characters ${ without starting interpolation, escape the dollar sign: `The token is \${amount}`. Escape sequences such as \n for a newline and \t for a tab are also available, as they are in ordinary string literals.
Common mistakes and problems
- Using quotes instead of backticks:
'Hello, ${name}'is an ordinary string, so JavaScript leaves${name}as literal characters. Change the surrounding quotes to backticks. - Omitting the dollar sign or braces:
`Hello, {name}`does not interpolate a variable. The exact form is${name}. - Putting invalid JavaScript inside a placeholder:
${first name}is not a valid expression. Use the actual variable name, such as${firstName}, or another valid expression. - Expecting automatic number or date formatting: a template literal converts a value to text, but it does not apply currency, rounding, or locale rules for you. Format the value before inserting it.
- Assuming interpolation makes HTML safe: inserting untrusted text into an HTML string does not escape it. If that string is interpreted as HTML, unsafe content can create a cross-site scripting risk. Prefer safe DOM APIs such as assigning untrusted text with
textContent, or use a suitable escaping or templating approach.
A related security point matters for database queries too: building a SQL command by inserting user input into a template literal is not a substitute for parameterized queries. Template literals are a string-writing feature, not a security boundary. The same caution applies whenever generated text is later interpreted as code, markup, a shell command, or another structured language.
Template literals versus concatenation
Before template literals, developers commonly joined strings and variables with the + operator. Both approaches remain valid, but templates are often easier to scan when a sentence includes several values.
const oldStyle = 'Hello, ' + firstName + '! You have ' + itemCount + ' messages.';
const templateStyle = `Hello, ${firstName}! You have ${itemCount} messages.`;
Concatenation can still be suitable for a small number of pieces, or when code is supporting an older JavaScript environment that does not parse template literals. It can also be useful when building a string incrementally in a loop, although repeatedly growing a string is not always the clearest design. For modern application code, choose the form that makes the intent easiest to understand; you do not need to replace every use of +.
One practical difference is that a template literal can span source lines directly. With concatenation, a multiline result usually requires explicit newline characters or multiple joined pieces. On the other hand, a long template with deeply nested expressions can become harder to read than a few named intermediate values.
How JavaScript differs from Python f-strings
The two features solve a similar problem but have different syntax and formatting tools. Python marks an f-string with a prefix and uses braces for expressions; JavaScript uses backticks and requires the dollar sign before the opening brace. A direct translation therefore needs a syntax change, not just a renamed prefix.
Python f-strings include format-specifier syntax inside a placeholder, such as instructions for decimal precision. JavaScript template literals do not define an equivalent format-specifier grammar. In JavaScript, call a method or formatter in the expression, or prepare the formatted value beforehand. Python also has its own conversion and debugging conveniences, so code using those features needs a considered rewrite rather than a mechanical replacement.
For example, a Python expression that formats a number to two decimal places should become JavaScript code that formats the number with a suitable JavaScript method or internationalization API, then inserts the result. This distinction is useful when translating examples, reading tutorials, or explaining why an f'...' expression copied from Python causes a syntax error in JavaScript.
Tagged templates and when to use them
Template literals have an advanced form called a tagged template. A function placed immediately before a template literal receives its fixed text segments and the values of its placeholders as arguments. The function can then process those parts and return a result; it is not simply the same as inserting values into a normal string.
function describe(strings, value) {
return `${strings[0]}${String(value).toUpperCase()}${strings[1]}`;
}
const result = describe`Status: ${'ready'}!`;
// Status: READY!
Tags are used by some libraries and tools to provide domain-specific behavior, such as structured query construction or specialized text processing. Their safety depends on the particular tag and how it handles values. A tag does not automatically make arbitrary HTML or SQL safe merely because it is attached to a template literal; check the library’s documented behavior.
If you are learning JavaScript or only need to insert values into a sentence, ordinary template literals are usually the right choice. Tagged templates are useful when a library explicitly provides one or when you have a clear reason to transform the literal segments and interpolated values.
Frequently Asked Questions
Does JavaScript have f-strings?
No. JavaScript has template literals, which provide interpolation using backticks and ${expression}. They resemble f-strings in everyday use but have different syntax and formatting features.
How do I write a string with a variable in JavaScript?
Use a template literal: `Hello, ${name}`. Make sure the string uses backticks, not single or double quotation marks, and put the JavaScript expression inside the braces.
Can I use template literals in Node.js and browsers?
Yes. Template literals are a standard JavaScript feature introduced in ECMAScript 2015 and are supported by modern Node.js releases and current browsers. If you must support an unusually old JavaScript engine, check its compatibility or use concatenation.
Can a template literal contain multiple lines?
Yes. A line break typed between the opening and closing backticks is included in the resulting string. Check the indentation in the source if the exact whitespace matters.
How do I print a literal ${ in a template literal?
Escape the dollar sign with a backslash, as in `\${name}`. The result contains the literal characters ${name} rather than evaluating name.
Do template literals escape HTML automatically?
No. They only build strings. Do not treat interpolated, untrusted content as safe HTML; use text-oriented DOM APIs or a purpose-built, documented escaping mechanism.
Related
- Balance of Payments Mind Map: Accounts and Flows
- Split a Part in Onshape: Steps, Uses, and Fixes
- Excel Goal Seek on Multiple Cells Explained
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Google Sheets Merge Cells Within a Table? What WorksNo. Google Sheets does not let you merge cells inside a Sheets table; to use merged cells, first…
- SUMIF Checkbox in Google Sheets: Sum Checked RowsIf your checkboxes are in A2:A20 and the values to add are in B2:B20, use =SUMIF(A2:A20,TRUE,B2:B20) to total…
- Google Sheets Conditional Formatting With IFYes. In Google Sheets, use Format > Conditional formatting, choose Custom formula is, and enter a formula that…
- How to Archive Deleted Emails in Outlook SafelyTo archive an email that is in Outlook’s Deleted Items folder, select it and move it to the…
- Google Sheets IFERROR: How It Works and When to Use ItIn Google Sheets, use IFERROR to show a useful alternative whenever a formula returns an error. For example,…
- 0.3-Inch Hanging Indent in Word: Set It Up PreciselyTo create a 0.3-inch hanging indent in Word, select the paragraph or paragraphs, open the Paragraph dialog, choose…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.