Reference article · Programming
JavaScript: functions, parameters and scope
A function groups instructions for a reusable task. It helps share calculations and understand an operation without reading the entire program.
Inputs and output
Parameters name a function’s inputs; arguments are the values supplied when calling it. return supplies a result and ends that execution. console.log displays a value but does not return it. A function without an explicit return yields undefined.
function calculateTotal(price, quantity) {
return price * quantity;
}
const total = calculateTotal(12, 3);
console.log(total); // 36Block scope
Scope determines where a variable is available. let and const have block scope: a name declared inside braces is unavailable outside that block. Use them after declaration; accessing them before initialization can cause a ReferenceError.
Arrow functions
An arrow with no braces implicitly returns its expression. With braces, write return to supply a result. Arrows differ from traditional functions, including having no this binding of their own. Either form can work for simple calculations.
const double = (value) => value * 2;
const triple = (value) => {
return value * 3;
};
console.log(double(4), triple(4)); // 8 12One clear responsibility
calculateTotal only multiplies its inputs. Separating calculation from display makes it easier to check and reuse. Decide what types it accepts and how it should handle negative quantities or text: JavaScript can convert some values automatically.
Practice specific cases
- Check calculateTotal(12, 0): it should return 0.
- Write a function that converts minutes into seconds.
- Try two inputs and verify the function does not accidentally depend on an outside variable.
References
Related articles
- Fundamentals: variables, conditions and loops
- Semantic HTML and page structure
- CSS: box model, Flexbox and Grid
- JavaScript: arrays, objects and data transformations
- DOM and events: connect JavaScript to HTML
- Promises, async/await and fetch requests
- HTTP and web APIs: requests, responses and status codes
- JSON: format, parsing and data validation
- Git: changes, commits, branches and remotes
- Node.js and npm: project scripts and dependencies
- Debugging and tests: finding and checking errors
- Colour formats: HEX, RGB and HSL
- UUID identifiers
- Random values in JavaScript
