JS Functions & Returns
Functions in JavaScript are block of code designed to perform a particular task. But to make them truly useful and dynamic, they need to take inputs (Arguments & Parameters) and give an output (Return).
Parameters vs Arguments
Often used interchangeably, but there's a distinct difference. Parameters are the variable names listed in the function definition. Arguments are the real, actual values passed to the function when you execute it.
// 'name' and 'age' are parameters
function greet(name, age) {
console.log("Hi " + name + ", age: " + age);
}
// "Alice" and 25 are arguments
greet("Alice", 25);The Return Keyword
When JavaScript reaches a return statement, the function will stop executing immediately. The value following the return keyword is passed back to whoever called the function.
If you don't explicitly return a value, the function will return undefined. Printing a value using console.log() inside a function is not the same as returning it!
Default Parameters (ES6)
You can assign default values to parameters. If no argument is passed during the call, the function defaults to that pre-assigned value instead of undefined.
function sayHello(name = "Stranger") {
return "Hello, " + name;
}
console.log(sayHello()); // "Hello, Stranger"Advanced Topic: Early Returns+
An "early return" is a pattern where you return from a function as soon as a condition is met, rather than using deep nested `if-else` blocks.
By using `return` early, you prevent the rest of the code in the function from running, acting as a natural break point and making your code significantly cleaner and easier to read.
