Function Expressions
1. Introduction
A function expression is a way to define a function by assigning it to a variable or passing it as a value. Unlike a function declaration, which stands on its own as a statement, a function expression is part of a larger expression syntax (typically an assignment statement).
Function expressions can be either anonymous (without a name) or named (with a local name that can be referenced inside the function body for recursion).
One of the most significant differences between function declarations and function expressions is hoisting. Function declarations are hoisted to the top of their enclosing scope, meaning they can be called before they are defined in the code. Function expressions, however, are not hoisted and cannot be called before they are defined.
2. Syntax, Examples, and Explanations
2.1 In JavaScript
In JavaScript, function expressions are extremely common. They allow functions to be treated as values (First-Class Citizens).
Syntax (Anonymous Function Expression):
const variableName = function(parameters) {
// function body
return value;
};
Syntax (Arrow Function Expression - ES6+):
const variableName = (parameters) => {
// function body
return value;
};
Example:
// Anonymous function expression
const add = function(a, b) {
return a + b;
};
console.log(add(5, 3)); // Output: 8
// Arrow function expression
const multiply = (a, b) => a * b;
console.log(multiply(5, 3)); // Output: 15
2.2 In Python
In Python, function expressions are represented by lambda expressions. Lambdas are small, anonymous, single-expression functions.
Syntax:
variable_name = lambda parameter1, parameter2: expression
Example:
# Lambda expression assigned to a variable
add = lambda a, b: a + b
print(add(5, 3)) # Output: 8
# Lambda expression for sorting key
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1])
print(pairs) # Output: [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]