Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery slanted/curly quotation marks confusion

I just came across this variation of appending a string containing a value stored in a variable, that I haven't seen before. Can anyone help me explain whats going on here?

This is what I came across:

var fruit = "banana"; 
$main = $('.main');

$main.append(`<p>${fruit} is a fruit.</p>`);
=> 'banana is a fruit.'

The slanted quotation marks seem to make a difference here, because this obviously doesn't do the trick:

$main.append('<p>$(fruit) is a fruit.</p>');
=> '$(fruit) is a fruit.'

It's probably something simple that I am not seeing right now. Can you explain to me, what's happening here? I couldn't find anything about these slanted quotation marks in Javascript/JQuery on the interwebs

Here is a simple Codepen to illustrate the issue:

http://codepen.io/lukastillmann/pen/MegXwQ

like image 460
lukastillmann Avatar asked Jan 07 '23 00:01

lukastillmann


1 Answers

The back-tick-delimited string literals are a syntax addition in JavaScript since EcmaScript2015: they indicate a template literal:

Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them. They were called "template strings" in prior editions of the ES2015 / ES6 specification.

Dollar signs and braces that occur within a template literal allow for "expression interpolation", which is what you see happening in your example.

Strings that are delimited by normal single or double quotes treat dollar signs and braces as literal characters; they do not support expression interpolation.

like image 98
trincot Avatar answered Jan 08 '23 15:01

trincot