Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this symbol () => mean in Javascript? [duplicate]

Tags:

javascript

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');
    });
like image 604
Sowmay Jain Avatar asked Jan 17 '17 16:01

Sowmay Jain


1 Answers

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.

like image 134
theonlygusti Avatar answered Sep 28 '22 00:09

theonlygusti