Robin Masters Robin Masters - 6 months ago 19
Node.js Question

Javascript Syntax. What is this: ", (err) => { }"?

I don't even know what to call it so not sure how to ask the question properly. What is the operator and what is it doing? I'm assuming its just passing a function expression as a callback, but the syntax is new to me.

(err) =>

fs.writeFile('message.txt', 'Hello Node.js', (err) => {
if (err) throw err;
console.log('It\'s saved!');
});

Answer

It is a so-called arrow function. It is a short form for defining function expressions. Hence,

fs.writeFile('message.txt', 'Hello Node.js', (err) => {
  if (err) throw err;
  console.log('It\'s saved!');
});

is basically similar to:

fs.writeFile('message.txt', 'Hello Node.js', function (err) {
  if (err) throw err;
  console.log('It\'s saved!');
});

Anyway, there is big difference bitween the syntaxes: While function creates a new scope for this, an arrow function re-uses the outer scope. Hence, in a callback defined using the function keyword you may need something such as

const that = this;

to preserve the outer scope, using an arrow function you don't need that. Please note that this also means that you are not able to use bind with an arrow function (i.e., it's not possible to redefine this for an arrow function (okay, to be true, you can use it, but the first parameter won't have any effect)).

Apart from that, please note that you can omit the parentheses around the parameter if there is only one. Hence, instead of

fs.writeFile('message.txt', 'Hello Node.js', (err) => {
  if (err) throw err;
  console.log('It\'s saved!');
});

you may also write:

fs.writeFile('message.txt', 'Hello Node.js', err => {
  if (err) throw err;
  console.log('It\'s saved!');
});

Anyway, this only works if there is only one parameter.

Comments