What is the purpose of template literals (backticks) following a variable definition in ES6?











up vote
24
down vote

favorite
1












In GraphQL you can write something like this to define a query:



const USER_QUERY = gql`
{
user(id: 2) {
name
}
}
`


In styled components you can define a styled component like this:



const Button = styled.button`
background-color: papayawhip;
`


What is this syntax? I know with template literals you can sub in variables with this syntax: ${foo} but I have never seen this used. Any guidance would be appreciated.










share|improve this question


















  • 2




    Where is this example coming from?
    – Hogan
    Nov 27 at 20:54






  • 1




    these are examples of how queries and styled components can be instantiated via those libraries, to exemplify the question on this syntax
    – Dacre Denny
    Nov 27 at 20:56






  • 3




    Tagged template literals?
    – HynekS
    Nov 27 at 20:57










  • Backticks calling a function || What is the usage of the backtick symbol (`) in JavaScript? (which mentions tagged template literal, but not in the first answer)
    – user202729
    Nov 28 at 4:25















up vote
24
down vote

favorite
1












In GraphQL you can write something like this to define a query:



const USER_QUERY = gql`
{
user(id: 2) {
name
}
}
`


In styled components you can define a styled component like this:



const Button = styled.button`
background-color: papayawhip;
`


What is this syntax? I know with template literals you can sub in variables with this syntax: ${foo} but I have never seen this used. Any guidance would be appreciated.










share|improve this question


















  • 2




    Where is this example coming from?
    – Hogan
    Nov 27 at 20:54






  • 1




    these are examples of how queries and styled components can be instantiated via those libraries, to exemplify the question on this syntax
    – Dacre Denny
    Nov 27 at 20:56






  • 3




    Tagged template literals?
    – HynekS
    Nov 27 at 20:57










  • Backticks calling a function || What is the usage of the backtick symbol (`) in JavaScript? (which mentions tagged template literal, but not in the first answer)
    – user202729
    Nov 28 at 4:25













up vote
24
down vote

favorite
1









up vote
24
down vote

favorite
1






1





In GraphQL you can write something like this to define a query:



const USER_QUERY = gql`
{
user(id: 2) {
name
}
}
`


In styled components you can define a styled component like this:



const Button = styled.button`
background-color: papayawhip;
`


What is this syntax? I know with template literals you can sub in variables with this syntax: ${foo} but I have never seen this used. Any guidance would be appreciated.










share|improve this question













In GraphQL you can write something like this to define a query:



const USER_QUERY = gql`
{
user(id: 2) {
name
}
}
`


In styled components you can define a styled component like this:



const Button = styled.button`
background-color: papayawhip;
`


What is this syntax? I know with template literals you can sub in variables with this syntax: ${foo} but I have never seen this used. Any guidance would be appreciated.







javascript ecmascript-6 graphql styled-components template-literals






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 27 at 20:53









Kurt William

19517




19517








  • 2




    Where is this example coming from?
    – Hogan
    Nov 27 at 20:54






  • 1




    these are examples of how queries and styled components can be instantiated via those libraries, to exemplify the question on this syntax
    – Dacre Denny
    Nov 27 at 20:56






  • 3




    Tagged template literals?
    – HynekS
    Nov 27 at 20:57










  • Backticks calling a function || What is the usage of the backtick symbol (`) in JavaScript? (which mentions tagged template literal, but not in the first answer)
    – user202729
    Nov 28 at 4:25














  • 2




    Where is this example coming from?
    – Hogan
    Nov 27 at 20:54






  • 1




    these are examples of how queries and styled components can be instantiated via those libraries, to exemplify the question on this syntax
    – Dacre Denny
    Nov 27 at 20:56






  • 3




    Tagged template literals?
    – HynekS
    Nov 27 at 20:57










  • Backticks calling a function || What is the usage of the backtick symbol (`) in JavaScript? (which mentions tagged template literal, but not in the first answer)
    – user202729
    Nov 28 at 4:25








2




2




Where is this example coming from?
– Hogan
Nov 27 at 20:54




Where is this example coming from?
– Hogan
Nov 27 at 20:54




1




1




these are examples of how queries and styled components can be instantiated via those libraries, to exemplify the question on this syntax
– Dacre Denny
Nov 27 at 20:56




these are examples of how queries and styled components can be instantiated via those libraries, to exemplify the question on this syntax
– Dacre Denny
Nov 27 at 20:56




3




3




Tagged template literals?
– HynekS
Nov 27 at 20:57




Tagged template literals?
– HynekS
Nov 27 at 20:57












Backticks calling a function || What is the usage of the backtick symbol (`) in JavaScript? (which mentions tagged template literal, but not in the first answer)
– user202729
Nov 28 at 4:25




Backticks calling a function || What is the usage of the backtick symbol (`) in JavaScript? (which mentions tagged template literal, but not in the first answer)
– user202729
Nov 28 at 4:25












2 Answers
2






active

oldest

votes

















up vote
25
down vote



accepted










These are tagged template literals. The part before the backpacks is a reference to a function that will be called to process the string.



The function is passed the variables (the ${} parts) as arguments as well as the pieces of the string that surround the variables broken into an array. The return value of the function becomes the value of the template. Because of this very generalized format, you can do almost anything with the function. Here's a quick and dirty example that takes the variables (gathered into an array for convenience), makes them uppercase, and puts them back in the string:






function upperV(strings, ...vars) {
/* make vars uppercase */
console.log("vars: ", vars) // an array of the passed in variables
console.log("strings:", strings) // the string parts

// put them together
return vars.reduce((str, v, i) => str + v.toUpperCase() + strings[i+1], strings[0]);
}

let adverb = "boldly"
let output = upperV`to ${adverb} split infinitives that no ${'man'} had split before...`;
console.log(output)








share|improve this answer






























    up vote
    15
    down vote













    Template literals have an additional feature called tagged templates. That's what the prefix before the opening backtick is. The prefix is actually the name of a function - the function is passed the constant parts of the template strings and the interpolated values (stuff in the ${} sections) and can process the resulting string into whatever it wants (although generally another string, doesn't have to be).



    See this page on MDN for more details on how tagged templates work.






    share|improve this answer





















    • "the function is passed the constant parts of the template strings" - what does this mean?
      – ESR
      Nov 28 at 3:31










    • It's the parts of the template string that aren't in the ${} blocks. Read the page I linked to, it has all the details.
      – Chris Tavares
      Nov 28 at 6:32











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53507972%2fwhat-is-the-purpose-of-template-literals-backticks-following-a-variable-defini%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    25
    down vote



    accepted










    These are tagged template literals. The part before the backpacks is a reference to a function that will be called to process the string.



    The function is passed the variables (the ${} parts) as arguments as well as the pieces of the string that surround the variables broken into an array. The return value of the function becomes the value of the template. Because of this very generalized format, you can do almost anything with the function. Here's a quick and dirty example that takes the variables (gathered into an array for convenience), makes them uppercase, and puts them back in the string:






    function upperV(strings, ...vars) {
    /* make vars uppercase */
    console.log("vars: ", vars) // an array of the passed in variables
    console.log("strings:", strings) // the string parts

    // put them together
    return vars.reduce((str, v, i) => str + v.toUpperCase() + strings[i+1], strings[0]);
    }

    let adverb = "boldly"
    let output = upperV`to ${adverb} split infinitives that no ${'man'} had split before...`;
    console.log(output)








    share|improve this answer



























      up vote
      25
      down vote



      accepted










      These are tagged template literals. The part before the backpacks is a reference to a function that will be called to process the string.



      The function is passed the variables (the ${} parts) as arguments as well as the pieces of the string that surround the variables broken into an array. The return value of the function becomes the value of the template. Because of this very generalized format, you can do almost anything with the function. Here's a quick and dirty example that takes the variables (gathered into an array for convenience), makes them uppercase, and puts them back in the string:






      function upperV(strings, ...vars) {
      /* make vars uppercase */
      console.log("vars: ", vars) // an array of the passed in variables
      console.log("strings:", strings) // the string parts

      // put them together
      return vars.reduce((str, v, i) => str + v.toUpperCase() + strings[i+1], strings[0]);
      }

      let adverb = "boldly"
      let output = upperV`to ${adverb} split infinitives that no ${'man'} had split before...`;
      console.log(output)








      share|improve this answer

























        up vote
        25
        down vote



        accepted







        up vote
        25
        down vote



        accepted






        These are tagged template literals. The part before the backpacks is a reference to a function that will be called to process the string.



        The function is passed the variables (the ${} parts) as arguments as well as the pieces of the string that surround the variables broken into an array. The return value of the function becomes the value of the template. Because of this very generalized format, you can do almost anything with the function. Here's a quick and dirty example that takes the variables (gathered into an array for convenience), makes them uppercase, and puts them back in the string:






        function upperV(strings, ...vars) {
        /* make vars uppercase */
        console.log("vars: ", vars) // an array of the passed in variables
        console.log("strings:", strings) // the string parts

        // put them together
        return vars.reduce((str, v, i) => str + v.toUpperCase() + strings[i+1], strings[0]);
        }

        let adverb = "boldly"
        let output = upperV`to ${adverb} split infinitives that no ${'man'} had split before...`;
        console.log(output)








        share|improve this answer














        These are tagged template literals. The part before the backpacks is a reference to a function that will be called to process the string.



        The function is passed the variables (the ${} parts) as arguments as well as the pieces of the string that surround the variables broken into an array. The return value of the function becomes the value of the template. Because of this very generalized format, you can do almost anything with the function. Here's a quick and dirty example that takes the variables (gathered into an array for convenience), makes them uppercase, and puts them back in the string:






        function upperV(strings, ...vars) {
        /* make vars uppercase */
        console.log("vars: ", vars) // an array of the passed in variables
        console.log("strings:", strings) // the string parts

        // put them together
        return vars.reduce((str, v, i) => str + v.toUpperCase() + strings[i+1], strings[0]);
        }

        let adverb = "boldly"
        let output = upperV`to ${adverb} split infinitives that no ${'man'} had split before...`;
        console.log(output)








        function upperV(strings, ...vars) {
        /* make vars uppercase */
        console.log("vars: ", vars) // an array of the passed in variables
        console.log("strings:", strings) // the string parts

        // put them together
        return vars.reduce((str, v, i) => str + v.toUpperCase() + strings[i+1], strings[0]);
        }

        let adverb = "boldly"
        let output = upperV`to ${adverb} split infinitives that no ${'man'} had split before...`;
        console.log(output)





        function upperV(strings, ...vars) {
        /* make vars uppercase */
        console.log("vars: ", vars) // an array of the passed in variables
        console.log("strings:", strings) // the string parts

        // put them together
        return vars.reduce((str, v, i) => str + v.toUpperCase() + strings[i+1], strings[0]);
        }

        let adverb = "boldly"
        let output = upperV`to ${adverb} split infinitives that no ${'man'} had split before...`;
        console.log(output)






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 28 at 5:16

























        answered Nov 27 at 20:58









        Mark Meyer

        31.9k32651




        31.9k32651
























            up vote
            15
            down vote













            Template literals have an additional feature called tagged templates. That's what the prefix before the opening backtick is. The prefix is actually the name of a function - the function is passed the constant parts of the template strings and the interpolated values (stuff in the ${} sections) and can process the resulting string into whatever it wants (although generally another string, doesn't have to be).



            See this page on MDN for more details on how tagged templates work.






            share|improve this answer





















            • "the function is passed the constant parts of the template strings" - what does this mean?
              – ESR
              Nov 28 at 3:31










            • It's the parts of the template string that aren't in the ${} blocks. Read the page I linked to, it has all the details.
              – Chris Tavares
              Nov 28 at 6:32















            up vote
            15
            down vote













            Template literals have an additional feature called tagged templates. That's what the prefix before the opening backtick is. The prefix is actually the name of a function - the function is passed the constant parts of the template strings and the interpolated values (stuff in the ${} sections) and can process the resulting string into whatever it wants (although generally another string, doesn't have to be).



            See this page on MDN for more details on how tagged templates work.






            share|improve this answer





















            • "the function is passed the constant parts of the template strings" - what does this mean?
              – ESR
              Nov 28 at 3:31










            • It's the parts of the template string that aren't in the ${} blocks. Read the page I linked to, it has all the details.
              – Chris Tavares
              Nov 28 at 6:32













            up vote
            15
            down vote










            up vote
            15
            down vote









            Template literals have an additional feature called tagged templates. That's what the prefix before the opening backtick is. The prefix is actually the name of a function - the function is passed the constant parts of the template strings and the interpolated values (stuff in the ${} sections) and can process the resulting string into whatever it wants (although generally another string, doesn't have to be).



            See this page on MDN for more details on how tagged templates work.






            share|improve this answer












            Template literals have an additional feature called tagged templates. That's what the prefix before the opening backtick is. The prefix is actually the name of a function - the function is passed the constant parts of the template strings and the interpolated values (stuff in the ${} sections) and can process the resulting string into whatever it wants (although generally another string, doesn't have to be).



            See this page on MDN for more details on how tagged templates work.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 27 at 20:57









            Chris Tavares

            18.8k33660




            18.8k33660












            • "the function is passed the constant parts of the template strings" - what does this mean?
              – ESR
              Nov 28 at 3:31










            • It's the parts of the template string that aren't in the ${} blocks. Read the page I linked to, it has all the details.
              – Chris Tavares
              Nov 28 at 6:32


















            • "the function is passed the constant parts of the template strings" - what does this mean?
              – ESR
              Nov 28 at 3:31










            • It's the parts of the template string that aren't in the ${} blocks. Read the page I linked to, it has all the details.
              – Chris Tavares
              Nov 28 at 6:32
















            "the function is passed the constant parts of the template strings" - what does this mean?
            – ESR
            Nov 28 at 3:31




            "the function is passed the constant parts of the template strings" - what does this mean?
            – ESR
            Nov 28 at 3:31












            It's the parts of the template string that aren't in the ${} blocks. Read the page I linked to, it has all the details.
            – Chris Tavares
            Nov 28 at 6:32




            It's the parts of the template string that aren't in the ${} blocks. Read the page I linked to, it has all the details.
            – Chris Tavares
            Nov 28 at 6:32


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53507972%2fwhat-is-the-purpose-of-template-literals-backticks-following-a-variable-defini%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Сан-Квентин

            8-я гвардейская общевойсковая армия

            Алькесар