I consider the life expectancy of all scientists:

const totalYears = inventors.reduce((total, inventor) => { return total + (inventor.passed - inventor.year); }, 0); alert(totalYears); 
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <script> const inventors = [{ first: 'Albert', last: 'Einstein', year: 1879, passed: 1955 }, { first: 'Isaac', last: 'Newton', year: 1643, passed: 1727 }, { first: 'Galileo', last: 'Galilei', year: 1564, passed: 1642 }, { first: 'Marie', last: 'Curie', year: 1867, passed: 1934 }, { first: 'Johannes', last: 'Kepler', year: 1571, passed: 1630 }, { first: 'Nicolaus', last: 'Copernicus', year: 1473, passed: 1543 }, { first: 'Max', last: 'Planck', year: 1858, passed: 1947 }, { first: 'Katherine', last: 'Blodgett', year: 1898, passed: 1979 }, { first: 'Ada', last: 'Lovelace', year: 1815, passed: 1852 }, { first: 'Sarah E.', last: 'Goode', year: 1855, passed: 1905 }, { first: 'Lise', last: 'Meitner', year: 1878, passed: 1968 }, { first: 'Hanna', last: 'Hammarström', year: 1829, passed: 1909 }]; </script> </body> </html> 

With the code, everything is clear, I don’t understand how to rewrite this expression using es6 string patterns:

 return total + (inventor.passed - inventor.year); 

I tried this way, it does not work:

 return `${total} ${inventor.passed} - ${inventor.year}`; 

but minus works as a symbol, if I understand correctly?

  • 2
    string patterns are needed to assemble a string . Inside reduce you collect a number . There is no point in using string patterns - Grundy
  • It is not clear what result you want to get - Grundy
  • @Grundy, by the way, yes, I did not read the whole question =) - Duck Learns to Take Cover
  • @Grundy okay.jpg, of course. it comes out too much here. I wanted to make the code more up to date. - spectre_it

1 answer 1

Whatever the task itself, about the use of string patterns :

${inventor.passed - inventor.year} , what is inside ${} is js, what is outside is a regular line.

  1. Simple examples of working with string patterns on es6-features .
  2. String patterns on mdn .
  3. Specification by string patterns .

Even in the switch functions it is very convenient to omit the curly braces and return

 (param, anotherParam) => { return param + anotherParam; } 

can be replaced by:
(param, anotherParam) => param + anotherParam

  • one
    here forEach is just an extra complication and use is not in its place. - Grundy
  • reduce is the same as forEach simply has no side effects. And the record with it looks much cleaner and without external variables - Grundy
  • In this case, exactly: (total, inventor) => total + (inventor.passed - inventor.year) - no += which changes the global variable, plus the result can be placed in const and not let so that it cannot be changed by chance :) - Grundy
  • (I still don’t like reduce, but Grundy convinced me that it doesn’t relate to the answer, so I deleted the mentions =)) - Duck Learns to Hide