A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/javascript/javascript-function-expression/ below:

JavaScript Function Expression - GeeksforGeeks

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.

JavaScript
const greet = function(name) {
    return `Hello, ${name}!`;
};
console.log(greet("Ananya"));

In this code

Syntax

const fName = function(params) {
    // function body
};
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!");
})();

Output
This is a self-invoking function!
Advantages of Function Expressions 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:

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.

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4