- 🧠 What are Functions?
- Function Declarations
- Parameters vs Arguments
- Return Values
- Function Expressions
- Arrow Functions
Functions are blocks of reusable logic designed to perform a specific task. Instead of repeating the same code again and again, you wrap it in a function and reuse it with different inputs to produce different results. This helps keep your code DRY (Don't Repeat Yourself).
Think of a function like a vending machine:
- Input (Parameters): You give it money and an item code.
- Logic (Function Body): The internal machinery processes the request (hidden from the user).
- Output (Return Value): It dispenses your selected item.
By using functions, you make your code:
- Modular: Break complex problems into smaller, manageable steps.
- Maintainable: Update the logic in one place, and it updates everywhere the function is used.
- Readable: Give descriptive names to blocks of code so others can easily understand what it does.
function greet() {
console.log("Welcome to Sheryians!");
}
greet();You define it once, then call it whenever needed.
function greet(name) {
console.log("Hello " + name);
}
greet("Harsh");- name is a parameter
- "Harsh" is the argument you pass
function sum(a, b) {
return a + b;
}
let total = sum(5, 10); // total is 15returnsends back a result to wherever the function was called- After
return, function exits
const greet = function () {
console.log("Hello!");
};- Functions stored in variables.
- Cannot be hoisted (you can’t call them before they’re defined)
const greet = () => {
console.log("Hi!");
};- Cleaner syntax
- No own this , no arguments object