Having trouble understanding the use of certain symbol in code below - javascript

I saw this code:
secondHand.style.transform = rotate(${secondsDegrees}deg);
I am struggling with the symbol that is wrapped around the code `rotate(${secondsDegrees}deg)`. I have not seen a ` used in javascript code before. The key is known as the acute, back quote, grave, grave accent, left quote, open quote, or the push key.
Any explanations would be appreciated!

`` Those are called backticks, and they create a template literal for easier insertion of variable values into strings, in JavaScript.
Example:
const someName = 'Jack'
const someTemplateLiteral = `${someName} and Jill went up a hill`
console.log(someTemplateLiteral)
// logs: 'Jack and Jill went up a hill'

This is a common string quote used in ES6 known as template literals.
Some commond examples:
`string text`
`string text line 1
string text line 2`
`string text ${expression} string text`
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 specification.
Check here - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

Related

How to use const value inside the string in JS

I'm writing React JS code for webpage.
The tutorial says the const value can be used inside the string with ${ } expression.
However, when I try it in my IDLE, it just recognize them as same string not const value.
What should I do to call saved const value inside the string
This is what it is supposed to be:
This is what I get instead:
async function getHeadlines(search) {
const url = 'https://newsapi.org/v2/top-headlines?country=au&apiKey={API_KEY}&q=${search}';
let res = await fetch(url);
let data = await res.json();
let articles = data.articles;
return articles.map((article) => ({
title: article.title,
url: article.url,
}));
}
You need to use backtick. Please go throught Template literals to understand how backtick works.
const url = `https://newsapi.org/v2/top-headlines?country=au&apiKey=${API_KEY}&q=${search}`;
As far as I can understand your question, you have to use template strings (check docs for more) for this URL:
const url = https://newsapi.org/v2/top-headlines?country=au&apiKey={API_KEY}&q=${search};
Now you can add API_KEY and search into a string.
Like everyone else said, you need to use backticks for template literals.
It looks like you are confusing non-template literal strings with template literals and their syntax (you forgot a $ in one of the literal block declarations). Let's have a little review, shall we?
Non-template literal strings look like this:
"This is a string with double quotes. It does not parse literals (${})";
'This is a string with single quotes. It does not parse literals (${})';
They use either single quotes (') or double quotes (").
Template literals are a special type of string, they allow insertion of variables and/or other data without having to use string concatenation ("This string " + "just got concatenated"). To do so, you have to wrap your code you want outputted in a ${} block, like this:
const textToInsert = "Hello, world!";
`This is a template literal. It is a string that allows easier concatenation without using the "+" operator. This parses literals, see? "${textToInsert}"`
Since the code is "executed", you can also use ternary operators:
`A random number I am thinking of is ${Math.floor(Math.random() * 10) >= 5 ? "greater than or equal to five" : "less than five"}`
Template literals are also useful if you use double quotes or single quotes in your string. If you use a single quote to declare a string that uses single quotes, you would have to escape them:
'It\'s a wonderful life'
The same applies to double quote strings using double quotes:
"\"I have no special talent. I am only passionately curious\" - Albert Einstein"
But, if you use template literals, you can use both single and double quotes without escaping them (note that you will have to escape backticks (`)):
`
It's a wonderful life.
"I have no special talent. I am only passionately curious" - Albert Einstein
`
Oh, I forgot to mention - template literals support newlines!!!
The conclusion? Template literals are powerful! You just have to know how to use them :)
So, what would your fixed template literal look like?
It would look like this:
`https://newsapi.org/v2/top-headlines?country=au&apiKey=${API_KEY}&q=${search}`;

How to use template literals (``) within template literals?

I have a very specific edge case which I need to use a template literal within a template literal but can't get it done.
The code looks something like this:
<p>Something something <a href={`${SOMELINK}/blah`}>SomeLink</a></p>
However I will have to wrap that in a function, while maintaining the value of the SOMELINK variable, this causes errors to happen. Whether I escape the ticks or not.
someFunction (`<p>Something something <a href={`${SOMELINK}/blah`}>SomeLink</a></p>`)
With escaped ticks I get the following error message:
Error: Expected SOMELINK but none provided
Without, I get:
Unexpected token, expected ","
How do I handle this?
Edit: It should probably be noted that the code being passed in someFunction will be rendered and it need to be used. It will eventually be passed in to another tag through dangerouslySetInnetHTML. So it will look something like this:
<div dangerouslySetInnerHTML={{__html: someFunction(`<p>Something something <a href={`${SOMELINK}/blah`}>SomeLink</a></p>`)}}/>
Not sure if this is relevant, but someFunction just does some modifications on the text.
I think you're overcomplicating it. If you only need to maintain the value of SOMELINK, this should work:
someFunction(`<p>Something something SomeLink</p>`)
You can do like:
someFunction(`<p>Something something <a href={${SOMELINK}/blah>SomeLink</a></p>`);
Try this
someFunction("<p>Something something <a href={"+`${SOMELINK}/blah`+"}>SomeLink</a></p>")
I think you also need to make the route relative
"<p>Something something <a href={/"+`${SOMELINK}/blah`+"}>SomeLink</a></p>"
Introduction
As imjared says in his answer, you're certainly complicating what a JavaScript template is. But I'd like to make it clearer by explaining the grammar of a template.
There are up to four different parts in a template and you can write a template within a template as I'll show you below, but not quite the way you mentioned it.
Fancy Strings
First of all, a template a nothing more than a fancy way to write a string with expressions defined within. If you type:
typeof `this template` (1)
in your browser console, it will write "string".
In the old days, when you wanted to concatenate many strings together, you would end up writing:
"string1" + "string2" + ... + "stringN" (2)
Some of the parameter could be numbers which would then be converted to string automatically (in most cases, it would work as expected). However, if you wanted to compute an expression, you most often had to write that expression between parenthesis:
"string1" + (a + b * c) + "string2" (3)
Modern JavaScript has Templates
Templates replace that with the ${...} special syntax. Within the ${...}, you can write your expression. This means (3) can be rewritten like follow using the template syntax:
`string1${a + b * c}string2` (4)
The syntax also has the advantage to look like you can insert a variable within a template like so:
`string1${varname}string2` (5)
This is still an expression, it just happens to be limited to varname.
As a result, you have four possible different parts in a template:
One String
If your template is just one string (i.e. no ${...}) then it is just like a string.
`this is just like a string` (6)
Two Parts
If you have one expression within a template, then you have a HEAD and a TAIL in your template. (4) and (5) above are templates with a HEAD and a TAIL.
Three Parts
If you write a template with more than one expression, that adds one or more special parts in between the expressions. These are called MIDDLE templates.
`head${expr1}middle${expr2}middle${expr3}tail` (7)
Templates Inside a Template
As I mentioned above, you can actually write a template inside a template. In most likelihood, you won't need such, but it is possible because what appears between the ${ and } is an expression and a template is viewed a primary literal (more or less, it's a tad bit more complicated than that...)
`string1${v
+ `sub-template${ sub_sub_template_is_possible }tail`
+ w}string2` (8)
As mention within the sub-template example in (8), you could have another sub-sub-template within the sub-template. I think that in most cases, you are not likely to need such since the root template already gives you all the necessary functionality.
Escape Characters
Templates, just like strings, support escaping various characters using the backslash as the introducer:
\<octal>
\x<hexadecimal>
\u<hexadecimal>
Some special characters such as the character n which represents the newline (\n)
Finally, the other characters are escaped as is, this would include:
\` (9)
to escape the template quotes, in which case they are viewed as the quote character, not a template starting or ending point. In other words, string (10) is equal to string (11):
`\`` (10)
"`" (11)
Very Much Simplified Grammar
Here are the parts mentioned above in simplified BNF-like syntax:
TemplateLiteral ::= Template
| TemplateHead TemplateExpression* TemplateTail
TemplateExpression ::= Expression
| TemplateExpression TemplateMiddle Expression
Template ::= '`' Character* '`'
TemplateHead ::= '`' Character* '${'
TemplateMiddle ::= '}' Character* '${'
TemplateTail ::= '}' Character* '`'
Character ::= ... -- characters valid in strings,
except '${' and '`' (12)
Reference
The JavaScript language is described in the ECMA-262 document found on this page:
https://www.ecma-international.org/publications-and-standards/standards/ecma-262/
Search for Template Literal Lexical Components. You will find the four parts (and much more) that I mentioned above: Template, TemplateHead, TemplateMiddle, and TemplateTail.
I think that SOMELINK variable is not available in that case.
You should provide SOMELINK first.

template strings not working [duplicate]

This question already has answers here:
Template literals like 'some ${string}' or "some ${string}" are not working
(7 answers)
Closed 3 years ago.
Template Strings should work on any terminals such as visual studio code terminal or windows terminal. But it didn't. I did this code visual studio code. Here is My code
var name = 'Andrew';
console.log('Hello ${name}');
and the output is
Hello ${name}
Please specify changes in my code needed and explain why it doesn't work currently.
Single and double quotes wont invoke the behavior - use back ticks.
var name = 'Andrew';
console.log(`Hello ${name}`);
// ^ ^
More information on Template literals,
All that is inside a string, is literal. You're writing the variable ${name} inside the normal quotes, so it will be printed literal.
If you want to have it interpretated, you have to concatenate the answer, as for example:
console.log('Hello ' + name)
The quotes to use a template are not the ones you are using, these are the correct ones: (closed accents / back-tick )
`Hello ${name}`
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
var name = 'Andrew';
console.log(`Hello ${name}`);
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 specification.
Template literals are enclosed by the back-tick (``) (grave accent) character instead of double or single or double quotes.
It's not a quote, nor double quote
var name = 'Andrew'
console.log(`Hello ${name}`)
Here is a tutorial about it: https://babeljs.io/learn-es2015/#template-strings

es6 multiline template strings with no new lines and allow indents

Been using es6 more and more for most work these days. One caveat is template strings.
I like to limit my line character count to 80. So if I need to concatenate a long string, it works fine because concatenation can be multiple lines like this:
const insert = 'dog';
const str = 'a really long ' + insert + ' can be a great asset for ' +
insert + ' when it is a ' + dog;
However, trying to do that with template literals would just give you a multi-line string with ${insert} placing dog in the resulting string. Not ideal when you want to use template literals for things like url assembly, etc.
I haven't yet found a good way to maintain my line character limit and still use long template literals. Anyone have some ideas?
The other question that is marked as an accepted is only a partial answer. Below is another problem with template literals that I forgot to include before.
The problem with using new line characters is that it doesn't allow for indentation without inserting spaces into the final string. i.e.
const insert = 'dog';
const str = `a really long ${insert} can be a great asset for\
${insert} when it is a ${insert}`;
The resulting string looks like this:
a really long dog can be a great asset for dog when it is a dog
Overall this is a minor issue but would be interesting if there was a fix to allow multiline indenting.
Two answers for this problem, but only one may be considered optimal.
Inside template literals, javascript can be used inside of expressions like ${}. Its therefore possible to have indented multiline template literals such as the following. The caveat is some valid js character or value must be present in the expression, such as an empty string or variable.
const templateLiteral = `abcdefgh${''
}ijklmnopqrst${''
}uvwxyz`;
// "abcdefghijklmnopqrstuvwxyz"
This method makes your code look like crap. Not recommended.
The second method was recommended by #SzybkiSasza and seems to be the best option available. For some reason concatenating template literals didn't occur to me as possible. I'm derp.
const templateLiteral = `abcdefgh` +
`ijklmnopqrst` +
`uvwxyz`;
// "abcdefghijklmnopqrstuvwxyz"
Why not use a tagged template literal function?
function noWhiteSpace(strings, ...placeholders) {
let withSpace = strings.reduce((result, string, i) => (result + placeholders[i - 1] + string));
let withoutSpace = withSpace.replace(/$\n^\s*/gm, ' ');
return withoutSpace;
}
Then you can just tag any template literal you want to have line breaks in:
let myString = noWhiteSpace`This is a really long string, that needs to wrap over
several lines. With a normal template literal you can't do that, but you can
use a template literal tag to allow line breaks and indents.`;
The provided function will strip all line breaks and line-leading tabs & spaces, yielding the following:
> This is a really long string, that needs to wrap over several lines. With a normal template literal you can't do that, but you can use a template literal tag to allow line breaks and indents.
I published this as the compress-tag library.

What's the difference between line breaks in template literals and '\' in string literals?

I was reading about template literals in the ES2015 spec which allows you to create (among other things) line breaks like so:
var brokenStr = `This is
a broken
string.`; //This is a broken string
We can also break a string literal with the backslash \ character.
var anotherBrokenStr = 'This is \
also a broken \
string.'; //This is also a broken string.
Is there a performance difference between the two? Which is considered best practice?
I have searched SO.
Update:
When I output as follows, I get a single line.
document.getElementById('logger').innerHTML = brokenStr;
When I use document.write() I get this in Chrome inspector:
This is also a broken string.
Which colapses the whitespace to a single space in the browser/
Update: Update:
It appears that the template literal includes a \n character. Then, is there any difference between the first example and this, or is it just syntax sugar?
var anotherBrokenStr = 'This is \\n
also a broken \\n
string.';
Here's the output of my Node.js REPL showing the difference between the two:
> `hello
... world`
'hello\nworld'
> 'hello\
... world'
'helloworld'
In the first case we get a newline between 'hello' and 'world'. In the second case we don't.
Edit: Dear Lord, you're thoroughly confused.
HTML doesn't
respect newlines.
It doesn't matter how many newlines
you put in between your lines.
HTML will still print it
as a single line.
Hope that makes things clear.

Categories

Resources