Open In App

JavaScript | template literals

Last Updated : 23 Oct, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

Template Literal in ES6 provides new features to create a string that gives more control over dynamic strings. Traditionally, String is created using single quotes (‘) or double quotes (“) quotes. Template literal is created using the backtick (`) character.

Syntax:

var s=`some string`;

Multiline Strings: In-order to create a multiline string an escape sequence \n was used to give new line character. However, Template Literals there is no need to add \n string ends only when it gets backtick (`) character.

  • Example:




    <script>
    // Without template literal
    console.log('Some text that I want \non two lines!');
      
    // With template literal
    console.log(`Some text that I want
    on two lines!`);
    </script>

    
    

  • Output:
    Some text that I want
    on two lines!
    Some text that I want
    on two lines!

Expressions: To dynamically add values into new Template Literals expressions are used. The ${} syntax allows an expression in it that produces the value. This value can be a string stored in a variable or a computation operation.

${expression}
  • Example : The code below shows the use of expressions in template literals.




    <script>
    let principal = 1000;
    let noofyears = 1;
    let rateofinterest = 7;
      
    let SI = `Simple Interest is ${(principal *
                noofyears * rateofinterest)/100}`;
    alert("Simple Interest is" + SI);
    </script>

    
    

  • Output:

Tagged Templates: One of the features of Template Literals is its ability to create Tagged Template Literals. Tagged Literal is written like a function definition, but the difference is when this literal is called. There is no parenthesis() to a literal call. An array of Strings are passed as a parameter to a literal.

  • Example 1:




    <script>
      
    function TaggedLiteralEg(strings) {
        document.write(strings);
    }
      
    TaggedLiteralEg `GeeksforGeeks`; 
      
      
    </script>

    
    

  • Output:
    GeeksforGeeks
  • Example 2: It is also possible to pass values to a tagged literal. This value can be a result of some expression or a value fetched from the variable. The code below shows the use of Tagged Literal.




    <script>
    function TaggedLiteralEg(strings, value, value2) {
        document.write(strings);
        document.write("<br>"+value2+"    "+value);
          
    }
      
    let text = 'GeeksforGeeks';
    TaggedLiteralEg`test ${text} ${2+3}`;    
    </script>

    
    

  • Output:
    test , ,
    5 GeeksforGeeks

Raw String: Raw method of template literal allows access of raw strings as they were entered, without processing escape sequences. In addition, the String.raw() method exists to create raw strings just like the default template function, and string concatenation would create.

  • Example:




    <script>
    var s=String.raw`Welcome to GeeksforGeeks Value of expression is ${2+3}`;
    document.write(s);
    </script>

    
    

  • Output:
    Welcome to GeeksforGeeks Value of expression is 5

Nested Templates: Templates can be nested if it contains multiple expression evaluation or multiple condition checking. Instead of using else if ladder this is readable and gives ease to the developer. The code below finds the maximum of three numbers using conditional operator and nested template literal.

  • Example:




    <script>
    function maximum(x, y, z) {
    var c = `value ${ (y>x && y>z) ? 'y is greater' :
    `${x>z ? 'x is greater' : 'z is greater'}` }`;
    return (c);
    }
    document.write(maximum(5, 11, 15)+"<br>");
    document.write(maximum(15, 11, 3)+"<br>");
    document.write(maximum(11, 33, 2)+"<br>");
    </script>                    

    
    

  • Output:
    value z is greater
    value x is greater
    value y is greater


Similar Reads

How to use template literals in Tailwind CSS to change classes dynamically ?
Tailwind CSS is a popular utility-first CSS framework used by many web developers to build modern and responsive user interfaces. It provides a wide range of pre-defined classes that can be used to style elements, but what if we want to dynamically change classes based on some condition or user input? This is where template literals come in handy.
6 min read
What are the template literals in ES6 ?
Template literals are a new feature that was introduced in ECMAScript6, which offers a simple method for performing string interpolation and multiline string creation. The template literals were called template strings before the introduction of ES6. Starting from ES6 (ECMAScript 6), we have Template Literals which are indicated by the backtick (`
3 min read
How to write multi-line strings in template literals ?
Template literals are introduced in ES6 and by this, we use strings in a modern way. Normally for defining string, we use double/single quotes ( " " or ' ' ) in JavaScript. But in template literals, we use backtick ( ` ` ). Let us see how to write multiline strings in template literals. Example 1: We write multiline string by template literals. C/C
1 min read
TypeScript Inference with Template Literals
TypeScript Inference with Template Literals helps to create specific types based on string patterns. However, they're not mainly used for making sure that an attribute's type matches its callback function's argument type. TypeScript uses different methods like inference and generics for that job. Template literal types are more about working with s
2 min read
How to use Template Literals in TypeScript ?
The template literal is a concise and flexible way of creating the dynamic string in TypeScript. The meaning of dynamic strings here is that they can be created using expressions like conditional statements, variables, or any other mathematical operation results that can be dynamically calculated at runtime and embedded in the strings. The template
1 min read
How to concatenate regex literals in JavaScript ?
Regex is a sequence of pattern that is used for matching with a pattern. While searching for data in a text, the search pattern is described for what we are searching for. It can be a single character or a more complex pattern. It can be used to perform all types of text searches. Regex has its own static and instance properties. Syntax: /pattern/m
2 min read
JavaScript SyntaxError - "0"-prefixed octal literals and octal escape sequences are deprecated
This JavaScript exception 0-prefixed octal literals and octal escape sequences are deprecated works in strict mode only. For octal literals, the "0o" prefix can be used instead. Message: SyntaxError: Octal numeric literals and escape characters not allowed in strict mode (Edge) SyntaxError: "0"-prefixed octal literals and octal escape sequences are
1 min read
Vue.js Custom Directives with Object Literals
Vue.js is a progressive javascript framework for developing web user interfaces. It is a performant, approachable, and versatile framework. We can create Single Page Applications as well as Full Stack applications. It is built on top of HTML, CSS, and Javascript which makes it easier for developers to integrate Vue.js in any application at any stag
4 min read
How to pass Variable to inline JavaScript using EJS Template Engine?
In the EJS templating engine, we can pass variables to inline JS within our HTML templates. We can use the '&lt;%= variable %&gt;' syntax, where we can embed server-side variables directly into the client-side scripts. In this article, we will explore the detailed process to pass a variable to inline javascript using the EJS templating engine in te
2 min read
How to Use Embedded JavaScript (EJS) as a Template Engine in Express JS ?
Embedded JavaScript (EJS) is a simple templating language that helps us to generate HTML markup with plain JavaScript. It's commonly used with Node.js to create dynamic web pages. It also helps to incorporate JavaScript into HTML pages. Approach to use EJS as Template Engine in Express JS:Install EJS: First, you need to install EJS in your Node.js
2 min read