JavaScript Template Literals: String Formatting Guide
This Snippet is coded by a user inOnline javascript Compiler. You can see and run this code too.
زبان: JavaScript
Template literals are JavaScript string literals wrapped in backticks. They support interpolation with ${expression}, allowing variables or expressions to be embedded directly instead of concatenating with plus signs. This example defines a user object and formats a greeting, a multiline report, a numbered task list, and a tagged-template highlight.
formatGreeting takes an object and returns a one-line string. formatTaskList maps each task to a numbered line and joins the results with newline characters. buildReport combines those helpers into a multiline report, including the task count. The highlight function is a tagged template: it receives the static string parts and interpolated values, then wraps each value in square brackets. Inputs are plain JavaScript values such as strings, arrays, objects, and dates; outputs are formatted strings logged to the console. Time complexity is O(1) for the greeting, O(n) for the task list where n is the number of tasks, and O(n) for the report because it processes all tasks. Space complexity is O(n) for the joined task list and report. Template literals improve readability, reduce concatenation errors, and make multiline output natural.