1

Lets say I have a Javascript function that adds two numbers as follows

function addNumbers(a, b){
return a+b;
}

Then I want to output to the console the result of calling the function with two numbers. When using string concatenation I can do the following:

console.log('The sum of two numbers is' +
addNumbers(a, b));

However, my question is how do I call the function if I want to use string interpolation? Something like:

 console.log(`the sum of two numbers 
    is addNumbers(a, b)`);
Ben
  • 139
  • 1
  • 2
  • 10

3 Answers3

3

As always, the expression you want to output the result of evaluating goes between ${ and }.

function addNumbers(a, b) {
  return a + b;
}

const a = 4;
const b = 6;

console.log(`the sum of two numbers 
    is ${addNumbers(a, b)}`);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

All you have to is wrap the expression with ${}

console.log(`the sum of two numbers is ${addNumbers(a, b)}`);

Template literals are enclosed by the back-tick (``) (grave accent) character instead of double or single quotes. Template literals can contain placeholders. These are indicated by the dollar sign and curly braces (${expression})

Marcos Casagrande
  • 37,983
  • 8
  • 84
  • 98
0

You can execute any expression inside of template literals (``) with a inside a $ and curly braces (${}).

Your example would look like this:

 console.log(`the sum of two numbers is ${addNumbers(a, b)}`);

See mdn docs for more information.

youngwerth
  • 602
  • 5
  • 11