JavaScript Function Expression
Last Updated : 16 Dec, 2024
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"));
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));
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));
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));
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!"); });
4. Self-Invoking Functions
Function expressions can be immediately executed.
JavaScript (function() { console.log("This is a self-invoking function!"); })();
OutputThis 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));
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
Feature | Function Expression | Function Declaration |
---|
Hoisting | Not hoisted; defined at runtime. | Hoisted; can be called before definition. |
Syntax | Defined within an expression. | Uses function keyword with a name. |
Usage | Useful for callbacks and dynamic functions. | Best for defining reusable functions. |
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
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.SyntaxFunction Declarationsfunction functionName( parameters ) { // Stateme
2 min read
Lambda Expressions in JavaScript A lambda expression also known as arrow-function is a function without a name defined using the arrow => syntax introduced in ES6 (ECMAScript 2015). Unlike traditional function declarations or expressions, lambda expressions are shorter and come with some unique behavior, particularly around the
5 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
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.JavaScriptfunction sum(x, y) { return x + y; } console.log(sum(6, 9)); // output: 15Function Syntax
5 min read