Function Expression in JavaScript

A function expression in JavaScript is a way to define a function as an expression, instead of as a declaration. Function expressions can be stored in a variable and they don’t need to have a name — these are often called anonymous functions. Function expressions are not hoisted, which means that you can’t call the function before it’s defined in your code.

Here is a simple example:

1
2
3
4
5
let sayHello = function(name) {
    console.log("Hello, " + name + "!");
};

sayHello("Alice"); // Outputs: Hello, Alice!

In this example, sayHello is a variable that holds a function. The function takes one parameter, name, and logs a greeting to the console using this parameter. After defining the function, you can call it using the variable name, sayHello, and passing in a string for the name parameter.

This is contrasted with a function declaration, where the function is declared and given a name, like this:

1
2
3
4
5
function sayHello(name) {
    console.log("Hello, " + name + "!");
}

sayHello("Alice"); // Outputs: Hello, Alice!

In this case, sayHello is a function declaration, and you can call it by its name directly, even before it’s defined due to function hoisting. Function expressions provide more flexibility in how and where you can define your functions. For example, they can be used as arguments to other functions (for callbacks), assigned as methods of objects, and so on.