Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to check whether a number is NaN or finite in JavaScript ?
Next article icon

What is a typical use case for anonymous functions in JavaScript ?

Last Updated : 02 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will try to understand what exactly an Anonymous function is, and how we could declare it using the syntax provided in JavaScript further we will see some examples (use-cases) where we can use anonymous functions to get our results in the console. Before proceeding with the examples or use cases of anonymous functions, let's briefly understand the simple function and anonymous function.

A function is a set of statements that take inputs, do some specific computation, and produce output. Basically, a function is a set of statements that performs some tasks or does some computation and then return the result to the user. The anonymous function works the same as the normal function but they differ in terms of syntax.

An anonymous function is a function that does not have any name associated with it. Normally we use the function keyword before the function name to define a function in JavaScript, however, in anonymous functions in JavaScript, we use only the function keyword without the function name. An anonymous function is not accessible after its initial creation, it can only be accessed by a variable it is stored in as a function as a value. An anonymous function can also have multiple arguments, but only one expression.

Example: Let's consider the following piece of code to understand how we declare a normal function and an anonymous function.

JavaScript
<script>     // Normal function     function Display() {          return "GeeksforGeeks!";      }            console.log(Display());       // Anonymous function       let display = function() {      return "GeeksforGeeks!!!";     }       console.log(display());  </script> 

Output:

GeeksforGeeks!  GeeksforGeeks!!!

Now let's see the following examples (use-cases) that would illustrate more about an anonymous function and its usage.

Example 1: In this example, we will store the anonymous function in a variable and then we will call that variable using the function calling syntax in order to print our result. If you don't know about the arrow function, please refer to the Arrow functions in JavaScript article.

JavaScript
<script>     let display = function() {         return "GeeksforGeeks...!";     }     console.log(display());             // Using arrow function         let displayName = () => {      return "GeeksforGeeks....!";        }       console.log(displayName());  </script> 

Output:

GeeksforGeeks...!  GeeksforGeeks....!

Example 2: In this example, we will pass a parameter inside our anonymous function that is responsible for taking our result name, and further while calling the function, we will provide the name as a parameter value.

JavaScript
<script>     let display = function(name) {         return name;     }        console.log(display("GeeksforGeeks"));             // Using arrow function        let displayName = (name) => {     return name;        }       console.log(displayName("GeeksforGeeks"));  </script> 

Output:

GeeksforGeeks  GeeksforGeeks

Example 3: In this example, we use an anonymous function as a self-invoking function (a special function that is invoked right after it is declared and also does not have any kind of name associated with it) and this can be done just by writing parenthesis in between the function definition.

JavaScript
<script>     (function () {       console.log("GeeksforGeeks....!");      })();          // Using arrow functions     (() => {         console.log("GeeksforGeeks....!");     })();  </script> 

Output:

GeeksforGeeks....!  GeeksforGeeks....!

Difference between the been Anonymous function & Normal function

S.No.

Normal function

Anonymous function

1. 

A simple function (also called a method) is responsible for carrying out certain operations or tasks. When the function is called, it executes that particular task for which the function has called.

An anonymous function is a function that does not have any name associated with it ie. this was created without any identifier or name that refer to it

2.

We can access this function directly by calling the function.

An anonymous function is not accessible after its initial creation, it can only be accessed by a variable it is stored in as a function as a value.

3. 

This function is useful for all scenarios. 

An anonymous function can be useful for creating IIFE(Immediately Invoked Function Expression).

4. 

Normal functions are hoisted which means we can declare the function after it has been used in javascript. 

An anonymous function can not be hoisted.


Next Article
How to check whether a number is NaN or finite in JavaScript ?
author
amansingla
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-functions
  • JavaScript-Questions

Similar Reads

  • How to write a function in JavaScript ?
    JavaScript functions serve as reusable blocks of code that can be called from anywhere within your application. They eliminate the need to repeat the same code, promoting code reusability and modularity. By breaking down a large program into smaller, manageable functions, programmers can enhance cod
    4 min read
  • What is Currying Function in JavaScript?
    Currying is used in JavaScript to break down complex function calls into smaller, more manageable steps. It transforms a function with multiple arguments into a series of functions, each taking a single argument. It converts a function with multiple parameters into a sequence of functions.Each funct
    3 min read
  • How to call JavaScript function in HTML ?
    In HTML, you can easily call JavaScript functions using event attributes like onclick and onload. Just reference the function name within these attributes to trigger it. You can also call functions directly within script blocks using standard JavaScript syntax. Let's create an HTML structure with so
    2 min read
  • setTimeout() in JavaScript
    The setTimeout() function is used to add delay or scheduling the execution of a specific function after a certain period. It's a key feature of both browser environments and Node.js, enabling asynchronous behavior in code execution. [GFGTABS] JavaScript setTimeout(function() { console.log('Hello
    2 min read
  • What is a typical use case for anonymous functions in JavaScript ?
    In this article, we will try to understand what exactly an Anonymous function is, and how we could declare it using the syntax provided in JavaScript further we will see some examples (use-cases) where we can use anonymous functions to get our results in the console. Before proceeding with the examp
    4 min read
  • How to check whether a number is NaN or finite in JavaScript ?
    When working with numbers in JavaScript, it's important to know how to determine if a value is NaN (Not-a-Number) or finite. This knowledge is crucial for data validation, error handling, and ensuring your code behaves as expected. In this article, we will see how to check whether the number is NaN
    3 min read
  • How to Encode and Decode a URL in JavaScript?
    Encoding and decoding URLs in JavaScript is essential for web development, especially when making GET requests with query parameters. This process ensures special characters in URLs are correctly interpreted by the server. For instance, spaces are converted to %20 or + in URLs. This guide covers how
    5 min read
  • How to declare the optional function parameters in JavaScript ?
    Declaring optional function parameters in JavaScript means defining function parameters that aren't required when the function is called. You can assign default values to these parameters using the = syntax, so if no argument is provided, the default value is used instead. These are the following ap
    3 min read
  • How to get the javascript function parameter names/values dynamically ?
    In this article, we are given any arbitrary JavaScript function and the task is to return the parameter names of the function. Approach: JavaScript contains a method called toString() which is used to represent a function code in its string representation. This method is used to get the parameter na
    2 min read
  • How To Include a JavaScript File in Another JavaScript File?
    The import and export syntax available in ES6 (ECMAScript 2015) module is used to include a JavaScript file in another JavaScript file. This approach is the most modern and recommended way to share code between JavaScript files. It allows you to break your code into smaller modules and then import t
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences