Understanding Tagged Template Literals in JavaScript

𝗨𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱𝗶𝗻𝗴 𝗧𝗮𝗴𝗴𝗲𝗱 𝗧𝗲𝗺𝗽𝗹𝗮𝘁𝗲 𝗟𝗶𝘁𝗲𝗿𝗮𝗹𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 Most of us use template literals in JavaScript like this: 𝗰𝗼𝗻𝘀𝘁 𝗻𝗮𝗺𝗲 = "𝗔𝗺𝗮𝗻"; 𝗰𝗼𝗻𝘀𝗼𝗹𝗲.𝗹𝗼𝗴(`𝗛𝗲𝗹𝗹𝗼 ${𝗻𝗮𝗺𝗲}`); But recently I explored something called Tagged Template Literals, and it is actually very powerful. What are Tagged Template Literals? A tagged template literal is 𝘄𝗵𝗲𝗻 𝘆𝗼𝘂 𝗽𝘂𝘁 𝗮 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝗯𝗲𝗳𝗼𝗿𝗲 𝗮 𝘁𝗲𝗺𝗽𝗹𝗮𝘁𝗲 𝘀𝘁𝗿𝗶𝗻𝗴. Here’s what happens internally: 𝘀𝘁𝗿𝗶𝗻𝗴𝘀 → 𝗮𝗻 𝗮𝗿𝗿𝗮𝘆 𝗼𝗳 𝘀𝘁𝗿𝗶𝗻𝗴 𝗽𝗮𝗿𝘁𝘀 𝘃𝗮𝗹𝘂𝗲 → 𝘁𝗵𝗲 𝗱𝘆𝗻𝗮𝗺𝗶𝗰 𝘃𝗮𝗹𝘂𝗲 𝗶𝗻𝘀𝗶𝗱𝗲 ${} So instead of directly returning a string, JavaScript passes the template literal to a function for custom processing. Tagged templates can be used for: • Custom formatting • Sanitizing user input • Building styled components • 𝗣𝗿𝗲𝘃𝗲𝗻𝘁𝗶𝗻𝗴 𝗫𝗦𝗦 𝗠𝗮𝗻𝘆 𝗹𝗶𝗯𝗿𝗮𝗿𝗶𝗲𝘀 𝗹𝗶𝗸𝗲 𝘀𝘁𝘆𝗹𝗲𝗱-𝗰𝗼𝗺𝗽𝗼𝗻𝗲𝗻𝘁𝘀 𝘂𝘀𝗲 𝘁𝗵𝗶𝘀 𝗰𝗼𝗻𝗰𝗲𝗽𝘁 𝗶𝗻𝘁𝗲𝗿𝗻𝗮𝗹𝗹𝘆. Have you ever used tagged template literals in a real project? Would love to know your use case. #javascript #webdevelopment #frontenddeveloper #reactjs #learning #developers

  • text

To view or add a comment, sign in

Explore content categories