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)`);
0

3 Answers 3

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)}`);

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for that explanation now I get it.
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})

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.