r/node • • Apr 14 '24

JavaScript Functions - 4 Ways

Post image
208 Upvotes

79 comments sorted by

View all comments

9

u/[deleted] Apr 14 '24

[removed] — view removed comment

8

u/BenjiSponge Apr 14 '24

The function expressions are all anonymous, but then they're given a name afterward.

Consider

function hof(fn) {
    setTimeout(() => console.log(fn(5)), 1000);
}

hof(x => x * x);

You could argue that this is "more anonymous", but it's also assigned into a variable called fn. It's no less or more anonymous than const square = x => x * x;.

You could maybe use an IIFE to be "truly anonymous", but... this is just splitting hairs really. Any function expression is an anonymous function.

11

u/jwalton78 Apr 14 '24

There are actually subtle differences between assigning a function to a variable and passing an anonymous function as a parameter. Assigning a function directly to a variable gives it a name (and the definition of an anonymous function is one that doesn't have a name):

function showName(x) { console.log(x.name) };

// Prints "square", because square is not in fact an anonymous function.
const square = (x) => x * x;
showName(square); 

// Prints "", because this is an anonymous function.
showName((x) => x * x);

3

u/BenjiSponge Apr 14 '24

Huh, didn't know that! Thanks for the info.

2

u/azhder Apr 14 '24

It’s an engine optimization.

It didn’t always do that and the difference can be seen if you do this:

const notTheName = function theActiualName(){};

1

u/azhder Apr 14 '24

I wouldn’t say they are given a name afterwards (although newer engines are smart to do so), but I would say a variable with certain name holds a reference to it.

1

u/rover_G Apr 14 '24

The arrow functions also don’t have a prototype. What that actually means I’m not sure.