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:
Lambda Expressions in JavaScript
Next article icon

JavaScript Function Expression

Last Updated : 16 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

A function expression is a way to define a function as part of an expression making it versatile for assigning to variables, passing as arguments, or invoking immediately.

  • Function expressions can be named or anonymous.
  • They are not hoisted, meaning they are accessible only after their definition.
  • Frequently used in callbacks, closures, and dynamic function creation.
  • Enable encapsulation of functionality within a limited scope.
JavaScript
const greet = function(name) {     return `Hello, ${name}!`; }; console.log(greet("Ananya")); 

Output
Hello, Ananya! 

In this code

  • The function(name) creates an anonymous function assigned to the greet variable.
  • The function takes name as a parameter and returns a greeting string.
  • Calling greet("Ananya") invokes the function and outputs the greeting.

Syntax

const fName = function(params) {     // function body };
  • fName: Variable storing the function.
  • function(params): Defines the function. Parameters are optional.
  • { // function body }: Contains the logic to execute when the function is called.

Named vs Anonymous Function Expressions

Anonymous Function Expression: The function has no name and is typically assigned to a variable.

JavaScript
const sum = function(a, b) {     return a + b; }; console.log(sum(5, 3)); 

Output
8 

Named Function Expression: The function is given a name, which is useful for recursion or debugging.

JavaScript
const factorial = function fact(n) {     if (n === 0) return 1;     return n * fact(n - 1); }; console.log(factorial(5)); 

Output
120 

Use Cases of Function Expressions

1. Storing in Variables

Function expressions are often assigned to variables for easy reuse.

JavaScript
const add = function(x, y) {     return x + y; }; console.log(add(3, 5));  

Output
8 

2. Callback Functions

They are commonly used as arguments in higher-order functions.

JavaScript
setTimeout(function() {     console.log("This message appears after 3 seconds!"); }, 3000); 

Output

This message appears after 3 seconds!

3. Event Handlers

Function expressions are ideal for event listeners.

JavaScript
document.querySelector("button").addEventListener("click", function() {     console.log("Button clicked!"); }); 

Output
[ 1, 4, 9, 16 ] 

4. Self-Invoking Functions

Function expressions can be immediately executed.

JavaScript
(function() {     console.log("This is a self-invoking function!"); })(); 

Output
This is a self-invoking function! 

Advantages of Function Expressions

  • Flexibility: Can be used as callbacks, event handlers, or part of expressions.
  • Encapsulation: Keeps the scope limited and avoids polluting the global namespace.
  • Control Over Execution: Executes only when explicitly invoked.

Arrow Functions: A Variant of Function Expressions

Arrow functions are a concise and modern way to define function expressions. They are particularly useful for short, single-purpose functions.

JavaScript
const arrowFunc = (param1, param2) => param1 + param2; console.log(arrowFunc(5, 7));  

Output
12 

Key Features:

  • Implicit return for single-line functions.
  • No binding of this, making them unsuitable for methods requiring a this context.

Function Expression vs Declaration

FeatureFunction ExpressionFunction Declaration
HoistingNot hoisted; defined at runtime.Hoisted; can be called before definition.
SyntaxDefined within an expression.Uses function keyword with a name.
UsageUseful for callbacks and dynamic functions.Best for defining reusable functions.

Next Article
Lambda Expressions in JavaScript

A

abhishekkharmale
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Methods

Similar Reads

  • JavaScript function* expression
    The function* is an inbuilt keyword in JavaScript which is used to define a generator function inside an expression. Syntax: function* [name]([param1[, param2[, ..., paramN]]]) { statements}Parameters: This function accepts the following parameter as mentioned above and described below: name: This p
    2 min read
  • JavaScript Function Examples
    A function in JavaScript is a set of statements that perform a specific task. It takes inputs, and performs computation, and produces output. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different
    3 min read
  • TypeScript Function Type Expressions
    In this article, we are going to learn about TypeScript Function Type Expressions in Typescript. TypeScript is a popular programming language used for building scalable and robust applications. In TypeScript, a function type expression represents the type of a function, including its parameter types
    3 min read
  • JavaScript Function Definitions
    JavaScript functions are declared using the function keyword, either as a declaration or expression. Declarations define named functions, while expressions assign functions to variables. Both enable code reuse and modularity. Syntax Function Declarations function functionName( parameters ) { // Stat
    3 min read
  • Lambda Expressions in JavaScript
    A lambda expression is a concise way to define a short function in programming. It's commonly found in modern languages like Python, Ruby, JavaScript, and Java. Essentially, it's just a small piece of code that creates a function. Thanks to functions being treated as objects in JavaScript, they can
    1 min read
  • Named Function Expression
    In JavaScript or in any programming language, functions, loops, mathematical operators, and variables are the most widely used tools. This article is about how we can use and what are the real conditions when the Named function Expressions. We will discuss all the required concepts in this article t
    3 min read
  • JavaScript Apply() Function
    The apply() method is used to write methods, which can be used on different objects. It is different from the function call() because it takes arguments as an array. Syntax: apply() Return Value: It returns the method values of a given function. Example 1: This example illustrates the apply() functi
    1 min read
  • JavaScript Anonymous Functions
    An anonymous function is simply a function that does not have a name. Unlike named functions, which are declared with a name for easy reference, anonymous functions are usually created for specific tasks and are often assigned to variables or used as arguments for other functions. In JavaScript, you
    3 min read
  • Functions in JavaScript
    Functions in JavaScript are reusable blocks of code designed to perform specific tasks. They allow you to organize, reuse, and modularize code. It can take inputs, perform actions, and return outputs. [GFGTABS] JavaScript function sum(x, y) { return x + y; } console.log(sum(6, 9)); [/GFGTABS]Output1
    5 min read
  • JavaScript Function() Constructor
    The JavaScript Function() constructor is used to create new function objects dynamically. By using the Function() constructor with the new operator, developers can define functions on the fly, passing the function body as a string. This allows for greater flexibility in situations where functions ne
    2 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