Hello, I would like to know the difference between these two types of quotes, it happens that with '' you don't get the keyCode and with `` you do and I don't understand why. Below is the code of the line where the scenario is presented.
const audio = document.querySelector('audio[data-key="${e.keyCode}"]');
The HTML and SCRIPT
<body>
<audio data-key="65" src="sounds/clap.wav"></audio>
<audio data-key="83" src="sounds/hihat.wav"></audio>
<audio data-key="68" src="sounds/kick.wav"></audio>
<audio data-key="70" src="sounds/openhat.wav"></audio>
<audio data-key="71" src="sounds/boom.wav"></audio>
<audio data-key="72" src="sounds/ride.wav"></audio>
<audio data-key="74" src="sounds/snare.wav"></audio>
<audio data-key="75" src="sounds/tom.wav"></audio>
<audio data-key="76" src="sounds/tink.wav"></audio>
<script>
window.addEventListener('keydown', function(e){
const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);
console.log(audio);
});
</script>
</body>
with ''
const audio = document.querySelector('audio[data-key="${e.keyCode}"]');
with ``
const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);
When you use the backticks ``, you are not representing a string itself, but rather you are using a function added in ES2015, called template strings, or template literals in English.
This feature allows you to create text strings using multiple lines of text and put values into it using
${expression}
what you're doing in your example, which evaluates${e.keycode}
before creating the final text string.This function is used to avoid having to concatenate strings using the operator
+
. I give you an example:Before the templates you would have to do this:
And with text templates you can make it easier:
Both of these examples will add the variable
nombre
to your string, you don't see much benefit in this little example, but when searching for longer or multi-line strings, they are a very useful tool.I leave you a link to the Mozilla Developer Network site with more information about this new function in JavaScript.
The inverted tilde is used to use the feature called ES2015 Template Strings
What it allows is to use variables that can be referenced in the middle of the string without having to break it into several sections concatenated by the symbol
+
Example
In your case the error is that when using single quotes
''
the string will be evaluated as it is written, without evaluating the variables inside${}
it and therefore you will get the following:While the correct thing would be