Difference between regular function and arrow function in JS?

Hi all. I’ve learned how to use function keyword and the () => {} (arrow function) keyword. And I was wondering about the difference between regular function and arrow function. :stuck_out_tongue:

For example with a regular function:

function myFunc() {
    console.log("Hello World!");
}
myFunc();
// or this
let yourFunc = function() {
    console.log("This is also an other function.");
}
yourFunc();

And the arrow function:

let ourFunc = () => {
    console.log("This is just like a regular function except it is made with an arrow function.");
}
ourFunc();

Please answer as fast as possible. :yum:

Thank you!
Pummarin :smile:

With the code you show, there is exactly no difference.

The only significant difference is that arrow functions aren’t executed in their own local context, so any reference to this in an arrow function refers to the context that cakes the arrow function.

So long as you aren’t using this, they’re the same.

2 Likes

What @snowmonkey said, and function declarations are hoisted. So you can do this:

sayHello();

function sayHello() {
  console.log('hello');
}

But you can’t do this:

// Uncaught ReferenceError: can't access lexical declaration 'sayHello' before initialization
sayHello();

const sayHello = () => {
  console.log('hello');
}
2 Likes

Hi @snowmonkey and @colinthornton. Thanks for the information. I read the MDN webpage and knows that there is no difference between regular function and arrow function. Thanks, guys!

Pummarin :smile:

Well, ish. I could as easily make a non hoisting function:

const sayHello = function(){...}

And just like that, it stayed put. Behind the scenes, a function declaration like you did is the same as

var sayHello = function sayHello(){...}

At least, that’s what javascript does. It creates a var by default, and sticks your function in.

The book You don’t know Javascript (Yet) dissects that point well.