DEV Community

Cover image for Anonymous and Arrow Functions in JavaScript
Shefali
Shefali

Posted on • Updated on • Originally published at shefali.dev

Anonymous and Arrow Functions in JavaScript

JavaScript provides various ways to define and use functions. Two commonly used types of functions are anonymous functions and arrow functions. In this blog, we will learn about these two functions in detail.

Letโ€™s get started!๐Ÿš€

Anonymous Functions

An anonymous function is a function that does not have any name. These functions are often defined inline and can be assigned to a variable or passed as an argument to another function.

Anonymous functions are useful when you need a quick function definition, and thereโ€™s no intention of reusing it elsewhere in the code.

Syntax of Anonymous Functions

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

// Invoking the anonymous function
myFunction();
Enter fullscreen mode Exit fullscreen mode

In this example, myFunction is an anonymous function assigned to a variable and you can invoke this function by using the variable name.

Use Cases of Anonymous Functions

Callback Functions

// Using an anonymous function as a callback
setTimeout(function() {
  console.log("This is invoked after 2 seconds");
}, 2000);
Enter fullscreen mode Exit fullscreen mode

In the above example, an anonymous function is given as an argument to another function.

Event Handlers

// Anonymous function as an event handler
document.querySelector("Button").addEventListener("click", function() {
  console.log("Button clicked!");
});
Enter fullscreen mode Exit fullscreen mode

When you want to attach an event handler dynamically, you can use the anonymous function.

Immediately Invoked Function Expressions (IIFE)

// IIFE using an anonymous function
(function() {
  console.log("This is an example of IIFE.");
})();
Enter fullscreen mode Exit fullscreen mode

If you want to create a function and execute it immediately after the declaration, then you can use the anonymous function like in the above example.

Array Methods

// Using anonymous function with array map method
const numbers = [1, 2, 3]
const doubledNumbers = numbers.map(function(num) {
  return num * 2;
});

console.log(doubledNumbers); // [2, 4, 6]
Enter fullscreen mode Exit fullscreen mode

You can use the anonymous functions with array methods like map, filter, and reduce.

Advantages of Anonymous Functions

  • Anonymous functions are often more concise in scenarios where a function is simple and wonโ€™t be reused.
  • When anonymous functions are used in IIFE patterns, they reduce the risk of variable conflicts in the global scope.

Limitations of Anonymous Functions

  • Anonymous functions can decrease the code readability.
  • With anonymous functions, debugging can be more challenging, as they lack meaningful names.
  • Anonymous functions have their own this binding, which may lead to unexpected behavior in certain contexts.

Arrow Functions

Arrow functions, introduced in ECMAScript 6 (ES6), provide a more concise syntax for writing functions. They are particularly useful for short and one-liner functions.

Syntax of Arrow Functions

// Basic arrow function
const add = (a, b) => {
  return a + b;
};
Enter fullscreen mode Exit fullscreen mode

If you have a single expression in the function body, then you can omit the curly braces {} and the return keyword as shown in the below example.

const add = (a, b) => a + b;
Enter fullscreen mode Exit fullscreen mode

If you have a single parameter in the function, then you can omit the parentheses around the parameter as shown in the below example.

const square = x => x * x;
Enter fullscreen mode Exit fullscreen mode

For functions, in which you have no parameters, you still need to include empty parentheses as shown in the below example.

const randomNumber = () => Math.random();
Enter fullscreen mode Exit fullscreen mode

Lexical this in Arrow Functions

One of the most significant features of arrow functions is that they do not have their own this binding. Instead, they inherit this from their parent scope. This behavior can be especially helpful when working with event handlers or callbacks within methods.

const obj = {
  name: "John",
  greet: () => {
    console.log(`Hello, ${this.name}`); // Lexical 'this' refers to the global scope, not obj
  }
};

obj.greet(); // Output: Hello, undefined
Enter fullscreen mode Exit fullscreen mode

In the above example, the arrow function greet does not have its own this binding, so it uses the this value from its parent scope, which is the global scope. Since name is not defined globally, it outputs undefined.

Use Cases of Arrow Functions

Array Manipulation

const numbers = [1, 2, 3, 4, 5];

// Using regular function
const squared = numbers.map(function (num) {
  return num * num;
});

// Using arrow function
const squaredArrow = numbers.map(num => num * num);
Enter fullscreen mode Exit fullscreen mode

Callback Functions

const numbers = [1, 2, 3, 4, 5, 6];

//Using regular function
const evenNumbers = numbers.filter(function(num) {
  return num % 2 === 0;
});

//Using arrow function
const evenNumbersArrow = numbers.filter(num => num % 2 === 0);
Enter fullscreen mode Exit fullscreen mode

Asynchronous Operations

const fetchFromAPI = () => {
  return new Promise((resolve, reject) => {
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => resolve(data))
      .catch(error => reject(error));
  });
};

fetchFromAPI().then(data => console.log(data));
Enter fullscreen mode Exit fullscreen mode

Advantages of Arrow Functions

  • Arrow functions have a more concise syntax, especially for short, one-liner functions.
  • Arrow functions do not have their own this binding. Instead, they inherit this from their parent scope.
  • Arrow functions often result in cleaner and more readable code, especially when used with array methods like map, filter, and reduce.

Limitations of Arrow Functions

  • Arrow functions do not have their own arguments object.
  • The concise syntax of arrow functions may lead to less descriptive function names, which can sometimes affect the code readability.
  • Arrow functions cannot be used as constructors, attempting to use new with an arrow function will result in an error.

Thatโ€™s all for today.

I hope it was helpful.

Thanks for reading.

For more content like this, click here.

You can also follow me on X(Twitter) for getting daily tips on web development.

Check out toast.log, a browser extension that lets you see errors, warnings, and logs as they happen on your site โ€” without having to open the browserโ€™s console. Click here to get a 25% discount on toast.log.

Keep Coding!!
Buy Me A Coffee

Top comments (9)

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.