Quick Overview
A function with no `return` gives back `undefined`, not nothing. Arguments are copied in, so reassigning a parameter changes only the local copy unless it is an object, where the reference is shared.
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().Write it yourself. The tests below run against your code.
Always ensure utility functions return explicit results. Next, let's peek under the hood at how JavaScript executes code using Execution Contexts!
Primitives copy by value and objects copy by reference, so `b = a` duplicates a number but shares an object. That single distinction explains most surprise mutations in a codebase.
`const` prevents reassignment, not mutation: a `const` object's properties can still be changed. `let` is scoped to its block, while `var` is function-scoped and leaks out of loops.
Only backticks interpolate: `${user}` reads the variable, while the identical text in quotes prints literally. Strings are immutable, so every method returns a new one rather than editing in place.