Usage of the backtick character (`) in JavaScript

后端 未结 9 2150
囚心锁ツ
囚心锁ツ 2020-11-22 00:51

In JavaScript, a backtick seems to work the same as a single quote. For instance, I can use a backtick to define a string like this:

var s         


        
9条回答
  •  时光说笑
    2020-11-22 01:26

    Summary:

    Backticks in JavaScript is a feature which is introduced in ECMAScript 6 // ECMAScript 2015 for making easy dynamic strings. This ECMAScript 6 feature is also named template string literal. It offers the following advantages when compared to normal strings:

    • In Template strings linebreaks are allowed and thus can be multiline. Normal string literals (declared with '' or "") are not allowed to have linebreaks.
    • We can easily interpolate variable values to the string with the ${myVariable} syntax.

    Example:

    const name = 'Willem';
    const age = 26;
    
    const story = `
      My name is: ${name}
      And I'm: ${age} years old
    `;
    
    console.log(story);

    Browser compatibility:

    Template string literal are natively supported by all major browser vendors (except Internet Explorer). So it is pretty save to use in your production code. A more detailed list of the browser compatibilities can be found here.

提交回复
热议问题