<aside> 💡
These are the building blocks of every JavaScript program. Master these and you can build anything.
</aside>
A function is a block of code you can run whenever you need it.
function welcome() {
console.log("Salaam!");
}
welcome(); // Salaam!
Mental model: Function = a reusable instruction. Like telling someone how to make shaah once. They can make it anytime after that.
Parameters — give the function inputs
function welcome(name) {
console.log("Salaam, " + name);
}
welcome("Ahmed"); // Salaam, Ahmed
welcome("Faadumo"); // Salaam, Faadumo
Multiple parameters
function add(a, b) {
return a + b;
}
let result = add(3, 5);
console.log(result); // 8
console.log vs return
function double(n) {
console.log(n * 2); // prints — but gives nothing back
}
function double(n) {
return n * 2; // gives the value back — you can use it
}
let result = double(5);
console.log(result); // 10
Without
returnthe function gives backundefined.
In practice
function calculateTotal(price, tip) {
return price + tip;
}
let total = calculateTotal(200, 1);
console.log(total); // 220
Mental model: Parameters = ingredients you hand to the function. Return = the finished result it hands back.
Variables live where they are created.