The JavaScript equivalent of f-strings in Python or string interpolation in other programming languages is template literals. Template literals allow for string interpolation and are enclosed in backticks (
) instead of single or double quotes. The ${}
syntax is used to embed variables within the string literal.
To embed variables within a template literal, you can use the ${}
syntax
const name = 'John';
const age = 30;
const message = `My name is ${name} and I'm ${age} years old.`;
console.log(message);
The variables name
and age
are embedded within the string using ${}
.
JavaScript f string equivalent example
Simple example code of using template literals in JavaScript:
Using template literals with conditional statements:
The conditional operator ?:
is used within the template literal to determine which number is greater.
<!DOCTYPE html>
<html>
<head>
<script>
const x = 10;
const y = 20;
const result = `The ${x > y ? 'greater' : 'less'} number is ${x > y ? x : y}.`;
console.log(result);
</script>
</head>
<body>
</body>
</html>
Output:
Using template literals with object properties:
const person = {
name: 'John',
age: 30
};
const message = `My name is ${person.name} and I'm ${person.age} years old.`;
console.log(message);
Using template literals with function calls:
function greet(name) {
return `Hello, ${name}!`;
}
const message = greet('John');
console.log(message);
Do comment if you have any doubts or suggestions on this JS string format topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version