[javascript] What does ${} (dollar sign and curly braces) mean in a string in Javascript?

I haven't seen anything here or on MDN. I'm sure I'm just missing something. There's got to be some documentation on this somewhere?

Functionally, it looks like it allows you to nest a variable inside a string without doing concatenation using the + operator. I'm looking for documentation on this feature.

Example:

_x000D_
_x000D_
var string = 'this is a string';_x000D_
_x000D_
console.log(`Insert a string here: ${string}`);
_x000D_
_x000D_
_x000D_

This question is related to javascript string variables concatenation

The answer is


You're talking about template literals.

They allow for both multiline strings and string interpolation.

Multiline strings:

_x000D_
_x000D_
console.log(`foo_x000D_
bar`);_x000D_
// foo_x000D_
// bar
_x000D_
_x000D_
_x000D_

String interpolation:

_x000D_
_x000D_
var foo = 'bar';_x000D_
console.log(`Let's meet at the ${foo}`);_x000D_
// Let's meet at the bar
_x000D_
_x000D_
_x000D_


As mentioned in a comment above, you can have expressions within the template strings/literals. Example:

_x000D_
_x000D_
const one = 1;_x000D_
const two = 2;_x000D_
const result = `One add two is ${one + two}`;_x000D_
console.log(result); // output: One add two is 3
_x000D_
_x000D_
_x000D_


You can also perform Implicit Type Conversions with template literals. Example:

let fruits = ["mango","orange","pineapple","papaya"];

console.log(`My favourite fruits are ${fruits}`);
// My favourite fruits are mango,orange,pineapple,papaya

Questions with javascript tag:

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax Drag and drop menuitems Is it possible to execute multiple _addItem calls asynchronously using Google Analytics? DevTools failed to load SourceMap: Could not load content for chrome-extension TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app What does 'x packages are looking for funding' mean when running `npm install`? SyntaxError: Cannot use import statement outside a module SameSite warning Chrome 77 "Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6 Why powershell does not run Angular commands? Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop Push method in React Hooks (useState)? JS file gets a net::ERR_ABORTED 404 (Not Found) React Hooks useState() with Object useState set method not reflecting change immediately Can't perform a React state update on an unmounted component UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block Can I set state inside a useEffect hook internal/modules/cjs/loader.js:582 throw err How to post query parameters with Axios? How to use componentWillMount() in React Hooks? React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory in ionic 3 How can I force component to re-render with hooks in React? What is useState() in React? How to call loading function with React useEffect only once Objects are not valid as a React child. If you meant to render a collection of children, use an array instead How to reload current page? Center content vertically on Vuetify Getting all documents from one collection in Firestore ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment How can I add raw data body to an axios request? Sort Array of object by object field in Angular 6 Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) Axios Delete request with body and headers? Enable CORS in fetch api Vue.js get selected option on @change Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) Angular 6: How to set response type as text while making http call

Questions with string tag:

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript How to change the datetime format in pandas How to write to a CSV line by line? convert string to number node.js "error: assignment to expression with array type error" when I assign a struct field (C) Remove 'b' character do in front of a string literal in Python 3 Ruby: How to convert a string to boolean What does ${} (dollar sign and curly braces) mean in a string in Javascript? How do I make a new line in swift converting json to string in python PHP - remove all non-numeric characters from a string C# - How to convert string to char? How can I remove the last character of a string in python? Converting std::__cxx11::string to std::string How to convert string to date to string in Swift iOS? Convert time.Time to string TypeError: a bytes-like object is required, not 'str' when writing to a file in Python3 How can I capitalize the first letter of each word in a string using JavaScript? Best way to verify string is empty or null Hive cast string to date dd-MM-yyyy Check for special characters in string How to convert any Object to String? Print "\n" or newline characters as part of the output on terminal Set the maximum character length of a UITextField in Swift How do I convert a Python 3 byte-string variable into a regular string? What does $ mean before a string? Delete the last two characters of the String Splitting a string into separate variables Figure out size of UILabel based on String in Swift Matching strings with wildcard How do I concatenate strings? Print very long string completely in pandas dataframe Check string for nil & empty Convert float to string with precision & number of decimal digits specified? How do I print my Java object without getting "SomeType@2f92e0f4"? enum to string in modern C++11 / C++14 / C++17 and future C++20 How should I remove all the leading spaces from a string? - swift Convert array to JSON string in swift Swift extract regex matches Convert a file path to Uri in Android How would I get everything before a : in a string Python

Questions with variables tag:

When to create variables (memory management) How to print a Groovy variable in Jenkins? What does ${} (dollar sign and curly braces) mean in a string in Javascript? How to access global variables How to initialize a variable of date type in java? How to define a variable in a Dockerfile? Why does foo = filter(...) return a <filter object>, not a list? How can I pass variable to ansible playbook in the command line? How do I use this JavaScript variable in HTML? Static vs class functions/variables in Swift classes? Passing Variable through JavaScript from one html page to another page Printing variables in Python 3.4 Python Function to test ping Declaring variable workbook / Worksheet vba Removing spaces from a variable input using PowerShell 4.0 How to modify a global variable within a function in bash? Bash: Echoing a echo command with a variable in bash set value of input field by php variable's value How to delete an instantiated object Python? Increment variable value by 1 ( shell programming) How to pass parameters or arguments into a gradle task How would I access variables from one class to another? What is a None value? How to remove a newline from a string in Bash Set environment variables from file of key/value pairs Convert dictionary to bytes and back again python? When should an Excel VBA variable be killed or set to Nothing? Add php variable inside echo statement as href link address? Getting the name of a variable as a string SQL variable to hold list of integers How can I do division with variables in a Linux shell? Append integer to beginning of list in Python ReferenceError: variable is not defined Length of string in bash Importing variables from another file? How can I print variable and string on same line in Python? jQuery: using a variable as a selector Create timestamp variable in bash script PHP: get the value of TEXTBOX then pass it to a VARIABLE How to base64 encode image in linux bash / shell Remove an element from a Bash array python: how to identify if a variable is an array or a scalar jQuery return ajax result into outside variable Pass variables between two PHP pages without using a form or the URL of page printf a variable in C Dynamic variable names in Bash How to check if a variable is an integer or a string? How can I test that a variable is more than eight characters in PowerShell? Assign command output to variable in batch file How to swap two variables in JavaScript

Questions with concatenation tag:

Pandas Merging 101 What does ${} (dollar sign and curly braces) mean in a string in Javascript? Concatenate two NumPy arrays vertically Import multiple csv files into pandas and concatenate into one DataFrame How to concatenate columns in a Postgres SELECT? Concatenate string with field value in MySQL Most efficient way to concatenate strings in JavaScript? How to force a line break on a Javascript concatenated string? How to concatenate two IEnumerable<T> into a new IEnumerable<T>? How to concat two ArrayLists? How to force addition instead of concatenation in javascript Fast way to concatenate strings in nodeJS/JavaScript How to concatenate and minify multiple CSS and JavaScript files with Grunt.js (0.3.x) Python concatenate text files How to concatenate items in a list to a single string? Combine two columns and add into one new column Concatenate in jQuery Selector Concatenating string and integer in python Logger slf4j advantages of formatting with {} instead of string concatenation How do I concatenate a boolean to a string in Python? Getting current date and time in JavaScript Append an array to another array in JavaScript Concatenating two one-dimensional NumPy arrays Python - How to concatenate to a string in a for loop? R - Concatenate two dataframes? Concatenating Matrices in R Scala list concatenation, ::: vs ++ concatenate two database columns into one resultset column Concatenate two string literals Concatenate multiple files but include filename as section headers PHP - concatenate or directly insert variables in string Easy way to concatenate two byte arrays Concat strings by & and + in VB.Net How can I get the concatenation of two lists in Python without modifying either one? Concatenating null strings in Java SQL UPDATE all values in a field with appended string CONCAT not working Casting an int to a string in Python Need to combine lots of files in a directory Python String and Integer concatenation How can strings be concatenated? How to concatenate int values in java? Can't concatenate 2 arrays in PHP How can I concatenate a string within a loop in JSTL/JSP? how to merge 200 csv files in Python Concatenate text files with Windows command line, dropping leading lines What do curly braces mean in Verilog? how to concatenate two dictionaries to create a new one in Python? How do I concatenate two lists in Python? Oracle SQL, concatenate multiple columns + add text StringBuilder vs String concatenation in toString() in Java