What if you could write a set of instructions once and use it anywhere without repeating yourself?
Why Function declaration in Javascript? - Purpose & Use Cases
Imagine you need to repeat the same set of instructions multiple times in your code, like calculating the area of different rectangles by writing the formula again and again.
Writing the same code repeatedly is slow and boring. It's easy to make mistakes, and if you want to change the formula, you have to find and fix every single place manually.
Function declaration lets you write the instructions once, give it a name, and then use that name whenever you need those instructions. This saves time, reduces errors, and makes your code cleaner.
let area1 = width1 * height1; let area2 = width2 * height2; // repeated calculation everywhere
function calculateArea(width, height) {
return width * height;
}
let area1 = calculateArea(width1, height1);
let area2 = calculateArea(width2, height2);It enables you to organize your code into reusable blocks that are easy to manage and update.
Think of a coffee machine: you press a button (call a function) to make coffee instead of manually mixing ingredients every time.
Functions let you reuse code easily.
They reduce mistakes by centralizing instructions.
They make your code cleaner and easier to read.