0

I'm working through 'The CLI Book - Writing Successful Command Line Clients with Node.JS by Robert Kowalski' and he uses a pattern that I haven't seen before in Javascript.

I've got some code below, which uses '=>' as something like an assignment, but I cannot understand what it does. I haven't seen Javascript use different assignment approaches that way 'R' might for example '=' vs '<-'.

const glob = require('glob');
const path = require('path');
const files = glob.sync('*.js');
var arr = files.map(file => path.resolve(file));
console.log(arr);

The output is:

[ '/Users/jon/dev/js/a.js',
  '/Users/jon/dev/js/glob.js',
  '/Users/jon/dev/js/prime.js' ]

It seems that the file value is being declared and assigned in one, but if I modify the return statement to be the following:

var arr = files.map(file = path.resolve(file));

then it doesn't work and I get the following:

var arr = files.map(file = path.resolve(file));
                                        ^
ReferenceError: file is not defined
    at Object.<anonymous> (/Users/jon/dev/js/a.js:4:41)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Function.Module.runMain (module.js:441:10)
    at startup (node.js:139:18)
    at node.js:968:3

I can't find reference to this '=>' operator anywhere in a bunch of books or on the web. He seems to use it in a number of places for example when defining a Promise:

function isOnline (url) {
  return new Promise((resolve, reject) => {
    request({
      uri: url,
      json: true
    }, (err, res, body) => {
.
.
.

Any thoughts on what this is and why specifically this is being used instead of a normal assignment?

Jon

Jon M
  • 530
  • 5
  • 17
  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions – Marc B Jul 21 '16 at 21:53
  • 1
    http://stackoverflow.com/questions/24900875/whats-the-meaning-of-an-arrow-formed-from-equals-greater-than-in-javas – Saad Jul 21 '16 at 21:53
  • Excellent - thanks. I actually looked for '=>' in stackoverflow but it returned nothing so decided to ask. – Jon M Jul 21 '16 at 21:55
  • Yeah, it can be a bit annoying to do a search of a symbol. It's usually better to google the name of the symbols in words to yield better search results. In this case, you would probably want to do something like "javascript arrow". – Saad Jul 21 '16 at 21:57

0 Answers0