0.5 Writing Functions & Logic From Scratch
A function is a reusable block of code designed to perform a specific task. Think of a function like a mini factory: you give it inputs, it processes them, and returns an output.
1. Function Structure & Vocabulary
- Parameters: Variables defined in the function signature to accept inputs (placeholders).
- Arguments: Actual values passed into the function when invoking/calling it.
- Return Statement: Outputs a value back to the caller and exits the function.
// Declaring a function with parameters (num1, num2)
function calculateTotal(num1, num2) {
let result = num1 + num2;
return result; // Output
}
// Calling/Invoking function with arguments (20, 30)
let total = calculateTotal(20, 30); // total is 50
2. Modern Arrow Functions (`() => {}`)
ES6 introduced arrow functions for clean, concise syntax:
// Standard Declaration
function multiply(a, b) { return a * b; }
// Arrow Function Syntax
const multiplyArrow = (a, b) => a * b;
3. Step-by-Step Blueprint: Writing Code From Scratch
Follow these 4 simple steps whenever solving a programming problem:
- Identify Inputs & Goal: What data do you have? What output do you want?
- Define Function Shell: Write
function myTask(param1) { ... } - Write Internal Logic: Use operators, conditionals (
if), or loops inside the function. - Return & Test: Return the result and call your function with
console.log().
📌 KEY POINTS TO REMEMBER
- Default Return: If a function does not have a
returnstatement, it automatically returnsundefined. - Parameters vs Arguments: Parameters are the variable names in function definition. Arguments are the real values passed when calling it.
- Function Scope: Variables declared inside a function cannot be accessed outside that function.
⚡ Interactive Visual: Function Machine
Simulate passing inputs into a function processor:
Click a function machine button above.