0

Can anyone explain these snippet (just line with the comment above) to me?

function wordRate(word, str) { 
    let words = str.match(/\w+/g) || []; 
    // What does these comparison or whatever it is?
    return words.filter(w => w == word).length / words.length; 
} 

Array.filter expects a function as first parameter: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

What is done here instead?

ts248
  • 311
  • 1
  • 4
  • 11
  • that's a new syntax - 'fat arrow function' https://googlechrome.github.io/samples/arrows-es6/ – Nitsan Baleli Mar 30 '16 at 06:14
  • The first parameter _is_ a function, specifically an [arrow function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) from ES6, the latest version of Javascript. This one returns a boolean. – Akshat Mahajan Mar 30 '16 at 06:14
  • it returns the value of `no of times the word appears/no of words in the string` – Arun P Johny Mar 30 '16 at 06:20

3 Answers3

1
(w => w == word)

is equivalent to

(function(w){return w == word})
Tope
  • 938
  • 2
  • 11
  • 15
1

To really understand this, you have to break it down.

ECMAScript 2015 (the latest version of Javascript, formerly ECMAScript 6) introduced arrow functions, which are essentially syntactic sugar for anonymous functions.

Instead of defining a cumbersome and wieldy expression like

function(x) { return x*x;}

arrow functions allow you to write instead

(x) => x*x 

where function parameters are specified in parenthesis and the returned result immediately follow the arrow.

In this particular example,

words.filter(w => w == word).length / words.length;

can be rewritten as

words.filter(function(w) {return (w == word);}).length / words.length;

This is easy to interpret: we're finding what fraction of the words array is made up of just a single target word.

Akshat Mahajan
  • 9,543
  • 4
  • 35
  • 44
0

so this is a Ecmascript 6 (javaScript 6) feature. look here https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions

TEST
  • 67
  • 7