Learn how functions accept input parameters, execute encapsulated logic, and return computed outputs for reusable modular code.
Learn how variables act as labeled containers for data using const, let, and var to manage lexical scope and reassignment safely in modern applications.
A function is a block of reusable code designed to perform a specific task when invoked (called).
Functions eliminate repetitive copy-pasting, isolate complex business rules into modular building blocks, and allow code to process dynamic arguments.
return Keywordreturn: Exits the function execution and passes the computed output back to the caller.// Function Declaration with parameters (length, width)
function calculateArea(length, width) {
const area = length * width;
return area; // Explicit return value
}
// Invocation with arguments (10, 5)
const roomArea = calculateArea(10, 5);
console.log(roomArea); // 50
Provide fallback values for parameters in case arguments are omitted during invocation:
function greetUser(name = "Guest", role = "Member") {
return `Welcome, ${name}! Role: ${role}.`;
}
console.log(greetUser()); // "Welcome, Guest! Role: Member."
console.log(greetUser("Sarah", "Admin")); // "Welcome, Sarah! Role: Admin."
return Keyword: If a function does not contain an explicit return statement, JavaScript automatically returns undefined when invoked!function doSomething() {} does NOT run the code inside it. You must explicitly invoke it: doSomething().Always ensure utility functions return explicit results. Next, let's peek under the hood at how JavaScript executes code using Execution Contexts!