DEV Community

Cover image for Anonymous and Arrow Functions in JavaScript

Anonymous and Arrow Functions in JavaScript

Shefali on February 05, 2024

JavaScript provides various ways to define and use functions. Two commonly used types of functions are anonymous functions and arrow functions. In ...
Collapse
 
kaitoito200198 profile image
kaitoito200198 • Edited

Nice!

It was help to me.
You are great.

Collapse
 
devshefali profile image
Shefali

I'm really happy this is helpful for you. Thank you so much for your feedbackπŸ™

Collapse
 
kaitoito200198 profile image
kaitoito200198

You are welcome.
Do you use discord?

Thread Thread
 
devshefali profile image
Shefali

No, I don't.

Thread Thread
 
kaitoito200198 profile image
kaitoito200198

then,what u use for chat?

Thread Thread
 
devshefali profile image
Shefali

I'm active on X(twitter).

Collapse
 
andylarkin677 profile image
Andy Larkin

it was interesting to read! I won’t be smart because I’m just learning a little myself

Collapse
 
devshefali profile image
Shefali

Thanks for checking out, Andy!

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

Interesting fact: as soon as you assign an anonymous function to a variable - it ceases to be anonymous. Your example shows an anonymous function defined with a function expression, being assigned to a variable. After assignment, the function's name will be myFunction - this can be checked by looking at the function's name property:

// Anonymous function assigned to a variable
var myFunction = function() {
  console.log("This is an example of an anonymous function.");
};

console.log(myFunction.name);  // 'myFunction' - it has a name! No longer anonymous
Enter fullscreen mode Exit fullscreen mode

Checking the name of an actual anonymous function does what you would expect:

console.log( (function() { console.log('Hello'); }).name );  // <empty string> - truly anonymous
Enter fullscreen mode Exit fullscreen mode

Similarly, arrow functions are also anonymous (the two are not mutually exclusive as your post implies). They also have no name unless assigned to a variable:

console.log( (() => console.log('Hello')).name );  // <empty string> - anonymous!

const myFunc = () => {};
console.log(myFunc.name);  // 'myFunc' - not anonymous
Enter fullscreen mode Exit fullscreen mode

An odd quirk with JS is that if you create a new function dynamically using the function constructor (new Function()) - it is given the name 'anonymous' - which is a contradiction, since having a name at all makes it NOT anonymous! πŸ˜›

More fun with anonymous functions here:

Another point worth making is that if you intend to remove an event handler, it's not a good idea to use an anonymous function as in your example - as you will have no easy reference to the function available in order to remove the handler.