Print var inside a string

I am new to JS and I want to know how to print var inside a string, I found that the path should be:

var user = {
    name: "Mike",
    sayHi:() => {
        console.log('Hi, I\'m ${name}');
    }
};

user.sayHi()

but I get: Hi, I'm ${name}

+4
source share
6 answers

Template literals use backreferences `` instead of regular quotes. ''

+6
source

If you want to use variables in a string, you must wrap them with reverse `ticks' instead of double or single quotes.

So the example below:

 console.log(`Hi, I'm ${name}`);
+4
source

('') (``) .

var user = {
name: "Mike",
sayHi:() => {
  console.log(`Hi, I\'m ${user.name}`);
}
};

user.sayHi()
Hide result

+3

console.log(`Hi, I'm ${name}`);

`backquote. Single quote '

EDIT: @peteb ,

+1

 console.log('Hi, I\'m ' + name);
0

This should be the back tick of a single quote. Below you will find

var user = {
    name: "Mike",
    sayHi:() => {
        console.log(`Hi, I\'m ${name}`);
    }
};

user.sayHi()
Run codeHide result
0
source

Source: https://habr.com/ru/post/1695165/


All Articles