DEV Community

Cover image for Function Expression vs Arrow Function Expression

Function Expression vs Arrow Function Expression

Oscar Ortiz on January 04, 2022

Introduction Let us learn the differences between a traditional function and an arrow function expression in JavaScript? If not, then pr...
Collapse
 
jonrandy profile image
Jon Randy šŸŽ–ļø • Edited

If we declare our function with a name, we can not change that function name elsewhere

This isn't really explained clearly. You have missed that you can also assign named functions to a variable:

const myFunction = function sayHello() { console.log( }
console.log(myFunction.name) // 'sayHello'
Enter fullscreen mode Exit fullscreen mode

This can actually be a good idea sometimes as (depending on the environment), stack traces can be easier to read if you give functions names. You are correct in stating that a function's name cannot be changed after the function is defined though.

Collapse
 
jonrandy profile image
Jon Randy šŸŽ–ļø • Edited

While writing this post I discovered that (at least in Chrome and Firefox) - if you create an 'anonymous' function in an assignment, it is not actually anonymous - it has the variable's name automatically given to it at the time of assignment:

const myFunction = function (i) { return i+1 }
console.log(myFunction.name) // 'myFunction'

const anotherFunction = myFunction
console.log(anotherFunction.name) // 'myFunction'
Enter fullscreen mode Exit fullscreen mode

So, it would seem that true anonymous functions are ones that are created outside of an assignment:

console.log( (function() {}).name ) // ''
console.log( (i=>i).name ) // ''
Enter fullscreen mode Exit fullscreen mode
Collapse
 
cleveroscar profile image
Oscar Ortiz

Thanks for the feedback! I'll make sure to make some changes.

Collapse
 
valzho profile image
Darren Doyle

You have an error in your arrow function examples. When omitting the curly braces {} from an arrow function body, i.e., single-line arrow functions, the results are automatically returned. (This, by the way, is a great feature of arrow functions as it reduces code.)

a => return a + 100; should be a => a + 100;

Collapse
 
therealmakariuz profile image
TheRealMakariuz

I’m new to JavaScript but this helped clear out overall doubts regarding this :)