6

You can see "(...)=>" symbol in the very first line of this code:

const server = http.createServer((req,res) => {
       res.statusCode = 200;
       res.setHeader('content-type', 'text/plain');
       res.end('Hello World');
    });
Sowmay Jain
  • 375
  • 2
  • 4
  • 12

2 Answers2

11

It's an arrow function, newly defined in ES6.

An arrow function expression has a shorter syntax than a function expression and does not bind its own this, arguments, super, or new.target. Arrow functions are always anonymous. These function expressions are best suited for non-method functions, and they cannot be used as constructors.


They are often just a shorter way of writing the anonymous function function () {}, with which you may already be familiar.

These pieces of code do the same thing:

  1. setTimeout(function () {
      console.log("Hey");
    }, 1000);
    
  2. setTimeout(() => {
      console.log("Hey");
    }, 1000);
    

This means that in your example http.createServer is accepting one argument, a function which itself takes two arguments.


Arrow functions are not equivalent to function () {} anonymous functions, function () {} binds its own this, for example.

theonlygusti
  • 11,032
  • 11
  • 64
  • 119
  • 1
    or, just don't because that's already *well* covered on the dupe. – Kevin B Jan 17 '17 at 16:37
  • I'm sure you know the difference, but too much simplification leads to misunderstanding very easily. It's like saying DOM getters return an array, and in the next question asker posts, they ask "why my `array.pop()` doesn't work". – Teemu Jan 17 '17 at 16:54
  • 1
    @Teemu but I haven't said that, I just hadn't specified fully the difference between them. I don't feel I did anything wrong. – theonlygusti Jan 17 '17 at 16:56
  • @Teemu I understand what you're saying, but I don't think it's quite so extreme a case. I said "Essentially, these pieces of code do the same thing." Which was true. It just can't be applied to all cases. – theonlygusti Jan 17 '17 at 17:02
  • 1
    They do the same thing, but are not equivalent. you didn't say they were equivalent, so you're not wrong – Kevin B Jan 17 '17 at 17:03
9

It is an ES6 Arrow function:

(req, res) => {}

is equivalent to:

function(req, res){}
Sheikz
  • 317
  • 1
  • 8
  • why did this get downvoted? It is actually correct, it isn´t lambda in JS as some might think, comparing it to other languages – Mikael Puusaari Jan 17 '17 at 16:48
  • 5
    it's a simplification of what arrow functions in JS are. They are more than just a shorthand for anonymous functions. You could even go so far as saying the two snippets in this answer are not equivalent. – Kevin B Jan 17 '17 at 16:49