0

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
  • 81
  • 1
  • 1
  • 9

3 Answers3

2

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
  • 857,932
  • 118
  • 1,152
  • 1,264
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
  • 33,668
  • 7
  • 72
  • 89
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