+ 3

jQuery(I think)

I have another question from a timed JavaScript Challenge. var x = `foo ${y}`, y = `bar ${x}`; console.log(x); // Output is: foo undefined I'm pretty sure that this is jQuery. As short as it is, I don't understand this code.

10th Jan 2019, 6:34 AM
DumbledoresAmy
DumbledoresAmy - avatar
4 odpowiedzi
+ 3
Are those ` (grave accent) instead of ' (single quote)? Some languages use this to evaluate some expression. What do you want x to be? A string containing "foo " and whatever ${y} is? Or the result of something called "foo"? But isn't y declared *after* x? So in any case it wouldn't make any sense like that. I assume this really is EcmaScript: the accent would be used for template strings. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals It just tries to replace ${y} with the value of y. But y is undefined. So that's what you get. I don't see what else you'd expect.
10th Jan 2019, 6:51 AM
Claude Martin
Claude Martin - avatar
+ 3
The basics of template literals are also covered in the lessons, in case you haven't come across it yet (third page): https://www.sololearn.com/learn/JavaScript/2969/
10th Jan 2019, 7:21 AM
Kishalaya Saha
Kishalaya Saha - avatar
+ 2
Thank you for the reply. The correct answer for this quiz question was "foo undefined". When I replaced the accents with single quotes, I got a different answer. I don't think I had ever seen them used before so I appreciate you sharing their name and what they do. Is $ notating jQuery? edit: sorry I just read the $ is part of template string syntax. Neat. 😎
10th Jan 2019, 6:59 AM
DumbledoresAmy
DumbledoresAmy - avatar
+ 2
The $ is a character that can be used as a variable, just like A or X. So when you import jQuery into your project it is literally doing var $ = jQuery. Template literals are a new way of writing strings. They have slightly different rules like ignoring line breaks and the ability to use variables inside them without needing to break the string and append another string. It does this with placeholder denoted by the ${x} expression. The above cannot possibly be jQuery, or any other library or variable because a variable followed by curly braces are simply not allowed, except now in template literals.
13th Jan 2019, 11:05 AM
Valtrius Malleus
Valtrius Malleus - avatar