Diffrence between ` and ' in Javascript?

What is the diffrence between ` and ’ in javascript? Which one should I use?
I’m doing the magic 8 ball lesson rn

Here is my code:
let userName = ‘Larry’;
userName ? console.log(‘Hello, ${userName}!’) : console.log(‘Hello!’);

The quotation mark I used was ’
But this code did not work. It prints:
Hello, ${userName}!

Here is the lesson tutorial’s code:
let userName = ‘Larry’;
userName ? console.log(Hello, ${userName}!) : console.log(‘Hello!’);

The quotation marks they used were `
This code works. It prints:
Hello, Larry!

Why is this?

To preserve code formatting in forum posts, see: How do I format code in my posts?

If you want embedded expressions to be evaluated, then you need to use backticks to create template literals (See documentation: Template literals (Template strings) - JavaScript | MDN)

For strings such as 'Larry' or 'Hello' or 'This is a string!!!', you can use single or double quotes.

However, if you want to evaluate embedded expressions such as variables, then you need to use backticks for template literals.

let name = "John"

// Quotes not suitable here
console.log('The name is ${name}') // "The name is ${name}" 

// Template literal (backticks) is suitable
console.log(`The name is ${name}`) // "The name is John"

let x = 10, y = 14
console.log('The sum of x and y is ${x+y}') // "The sum of x and y is ${x+y}"
console.log(`The sum of x and y is ${x+y}`) // "The sum of x and y is 24"
console.log(`The sum of ${x} and ${y} is ${x+y}`) // "The sum of 10 and 14 is 24"
2 Likes

I see, thank you so much!

1 Like