简体   繁体   中英

How to use template literals of ES6 script

I have been trying to solve a template literal question on hackerrank. It works fine on my local IDE but giving error on Hackerrank IDE. Heres the code two add two number and to print the result using template literal.

const sum = () => {
  let a=1;
  let b=2;
  console.log(`The sum of ${a} and ${b} is ${a + b}`);
}
module.exports = {sum}

But it is producing the following error.

npm WARN template-literals@1.0.0 No repository field.

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules/fsevents):

npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.9: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

audited 522 packages in 6.264s

found 611 vulnerabilities (378 low, 233 high)

  run `npm audit fix` to fix them, or `npm audit` for details

> template-literals@1.0.0 test /projects/challenge

> mocha test --reporter mocha-junit-reporter

The sum of 1 and 2 is 3

npm ERR! Test failed.  See above for more details.

I would like to add my view.

const sum = (a,b) => {
  return `The sum of ${a} and ${b} is ${a + b}`;
};
module.exports = {sum}

Semicolons are important in these type of code

Here's a simple example.

const sum = (a = 1, b = 2) => {
    return `The sum of ${a} and ${b} is ${a + b}`;
}

Here's the explanation.

const sum =          Create a variable named `sum`.
(a = 1, b = 2) => {  Create an arrow function, with variables `a` and `b`, with defaults of 1 and 2 respectively.
return `             Return a string. In addition to " and ', a backtick will create a string, but with benefits!
${a}                 Interpolate the variable `a` into the string.
${b}                 Interpolate the variable `b` into the string.
${a + b}             Interpolate the expression of `a + b`.
`;                   End the string.

Here's an example of what the code would look like without interpolation.

const sum = (a = 1, b = 2) => {
    return 'The sum of ' + a + ' and ' + b + ' is ' + (a + b);
}

const sum = (a, b) => { return( The sum of ${a} and ${b} is ${a+b} ); }

A template literal is used to interpolate values into strings without concatenating.

Here is an example of how to interpolate parameters a and b into a string:

const sum = (a, b) => {
   return `The sum of ${a} and ${b} is ${a+b}`;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM