0

I am exploring arrow functions, I came up with this basic example, I just need to understand how the follwing works

var getServer = () => {
    if(document.getElementById('server')){
        var serverHTML = document.getElementById('server');
        serverHTML.innerHTML = "Server: " + window.location.host;
    }
    if(document.getElementById('serverxs')){
        var serverHTMLxs = document.getElementById('serverxs');
        serverHTMLxs.innerHTML = "Server: " + window.location.host;
    }
};

The getServer = () => part is confusing how is empty brackets correct? Or am I wrong.

Any documentation or answers appreciated

2 Answers2

3

You can "read" arrow functions like this

(par1, par2) => "value"

turns into

function(par1, par2){ return "value"; }

So:

() => 

turns into a function with no parameters passed to it. An exception to this is when one argument is passed to an arrow function, so:

param=>{ return value; }
// turns into
function(param){ return value; }
user7951676
  • 377
  • 2
  • 10
Luca De Nardi
  • 2,280
  • 16
  • 35
1

It's a function without parameters, as short/arrow function:

var getServer = () => { /* ... */ }
// matches
var getServer = function (){ /* ... */}

// Example:
var example = function (foo, bar){ return foo;}
// matches
var example = (foo, bar) => { return foo;}

There are some caveats though, which you might want to check.

Martijn
  • 15,791
  • 4
  • 36
  • 68
  • * with all the caveats described in this post https://stackoverflow.com/questions/34361379/arrow-function-vs-function-declaration-expressions-are-they-equivalent-exch – John Oct 31 '17 at 11:05
  • I've added it to my post so it gets read better :) For simple functions they're the same, but it might get confusing fast. – Martijn Oct 31 '17 at 11:07
  • I tried using it in one of my projects but the arguments got a little confusing – Andrew Christopher Nov 01 '17 at 11:03