What is a function?
A function in JavaScript is a block of code designed to perform a specific task.
Instead of writing the same code again and again, you can write it once inside a function and reuse it whenever needed.
๐ก Simple idea
A function is like a machine: you give input, it does something, and gives output.
Why do we use functions?
- โป๏ธ Reusability โ write once, use many times
- ๐งน Clean code โ better organization
- ๐ Easier debugging
- โก Less repetition
Function syntax
// function declaration function greet() { console.log("Hello!"); }
Calling a function
A function only runs when you call it:
greet(); // Hello!
Functions with parameters
Functions can take inputs called parameters.
function greet(name) { console.log("Hello " + name); } greet("Rahul"); greet("Aisha");
Functions with return values
Functions can also return results.
function add(a, b) { return a + b; } let result = add(5, 3); console.log(result);
Types of functions
- Function declaration
- Function expression
- Arrow functions
// arrow function const multiply = (a, b) => a * b;
Real-world usage
- Handling button clicks
- Form validation
- Calculations
- API calls
- UI updates
Summary
Functions are reusable blocks of code that perform tasks. They are one of the most important building blocks in JavaScript programming.
Once you understand functions, you can build much more powerful programs.