17

I am learning node js, and came across '=>' several times, however struggle to understand what this means.

Here is an example:

app.post('/add-item', (req, res) => {
  // TODO: add an item to be posted
});

Do we actually need this in the above example? A simple explanation would be helpful. Thanks

Jens Mühlenhoff
  • 13,744
  • 6
  • 47
  • 101
deeveeABC
  • 902
  • 2
  • 9
  • 30

2 Answers2

41

It's nothing node-exclusive, it's an ES6 Arrow function expression

app.post('/add-item', (req, res) => {
  // TODO: add an item to be posted
});

basically means:

app.post('/add-item', function(req, res) {
  // TODO: add an item to be posted
});

The main difference between these two examples is that the first one lexically binds the this value.

roberrrt-s
  • 7,249
  • 2
  • 41
  • 53
  • 4
    good answer, but I doubt `lexically binds the this value` means much to someone that thinks `=>` is exclusive to node.js – Christopher Reid Sep 05 '16 at 10:15
  • 10
    Yes @AllTheTime, but this could be usefull for anyone else that is looking for `=>` information. Therefor, I included it. – roberrrt-s Sep 05 '16 at 10:54
  • 3
    Nothing special about it. Lexical binding is a fancy word for static binding which in turn means that `this` doesn't change inside the anonymous function and always points to the object containing it. –  Jun 16 '19 at 16:53
1

This is just a different way of writing an anonymous function:

$(document).ready(() => {
    console.log('Hello I am typescript');
});

is equivalent to JavaScript:

$(document).ready(function(){
    console.log('Hello I am typescript');
});
11684
  • 7,120
  • 10
  • 45
  • 69
Vishal Gupta
  • 132
  • 2
  • 6
  • it has two different, default return value on one-liners (no { }) and this is kept from the parent context (that's what you want for callbacks all the time most likely and better use regular functions otherwise) – localhostdotdev May 17 '19 at 00:02