Module 5: Functions
Function Expressions and Arrow Functions
Function Expression: A function can also be defined as an expression and assigned to a variable. This is called a function expression.
// Function expression const multiply = function(a, b) { return a * b; }; let product = multiply(4, 5); console.log(product); // Output: 20
Function expressions are not hoisted in the same way as function declarations, meaning you must define them before you can call them.
Arrow Functions (ES6+): Arrow functions provide a more concise syntax for writing function expressions. They are especially useful for simple, one-line functions.
Basic Syntax:
(param1, param2, ..., paramN) => expression
(implicitly returns expression
)
Or for multiple statements:
(param1, param2, ..., paramN) => { // statements return value; // Explicit return needed for multi-line blocks }
Examples:
// Traditional function expression const addOld = function(a, b) { return a + b; }; // Arrow function (concise body, implicit return) const addArrow = (a, b) => a + b; console.log(addArrow(3, 7)); // Output: 10 // Arrow function with multiple statements (explicit return) const greetArrow = (name) => { let message = "Hello, " + name; return message; }; console.log(greetArrow("Developer")); // Output: Hello, Developer // Arrow function with no parameters const sayHi = () => console.log("Hi!"); sayHi(); // Output: Hi! // Arrow function with one parameter (parentheses optional) const double = x => x * 2; console.log(double(5)); // Output: 10
Key differences with traditional functions:
this
keyword binding: Arrow functions do not have their ownthis
context. They inheritthis
from the surrounding (lexical) scope. This is a significant difference and often beneficial in callbacks and methods.- No
arguments
object: Arrow functions do not have their ownarguments
object. You can use rest parameters (...args
) instead. - Cannot be used as constructors (cannot be called with
new
).