JavaScript Functions
5 April 2025 | Category: JavaScript
📌 What is a Function?
A function is a block of code designed to perform a task. You can reuse this block anywhere in your code, saving time and avoiding repetition.
âś… Why Use Functions?
- Code reusability
- Better organization
- Easier debugging and maintenance
- Avoid repetition (DRY – Don’t Repeat Yourself)
🛠️ 1. Function Declaration (Named Function)
function greet() {
console.log("Hello there!");
}
greet(); // Call the function
- The
function
keyword defines a function. greet
is the function name.()
holds parameters (if any).{}
contains the function code (body).
đź§ľ 2. Function with Parameters
function greetUser(name) {
console.log("Hello, " + name);
}
greetUser("Alice");
greetUser("Bob");
name
is a parameter."Alice"
and"Bob"
are arguments passed to the function.
đź”™ 3. Function with Return Value
function add(a, b) {
return a + b;
}
let result = add(5, 3);
console.log(result); // Output: 8
return
sends a value back to the place where the function was called.
🧑‍💻 4. Function Expressions
const multiply = function(x, y) {
return x * y;
};
console.log(multiply(4, 5)); // Output: 20
- Functions can be stored in variables.
- These are anonymous functions (no name).
⚡ 5. Arrow Functions (ES6+)
const divide = (a, b) => {
return a / b;
};
console.log(divide(10, 2)); // Output: 5
- Shorter syntax using
=>
- If there’s only one statement, you can write it even shorter:
const square = n => n * n;
console.log(square(4)); // Output: 16
♻️ 6. Default Parameters
function greet(name = "Guest") {
console.log("Welcome, " + name);
}
greet(); // Welcome, Guest
greet("Sam"); // Welcome, Sam
- If no argument is passed, default is used.
📦 7. Rest Parameters (...
)
function sum(...numbers) {
let total = 0;
for (let num of numbers) {
total += num;
}
return total;
}
console.log(sum(1, 2, 3, 4)); // Output: 10
- Collects all extra arguments into an array-like object.
🔍 8. Function Scope
function testScope() {
let a = 10; // local to function
console.log(a);
}
testScope();
// console.log(a); ❌ Error: a is not defined
- Variables declared inside a function are local to that function.
đź§ Summary
Type | Syntax Example |
---|---|
Function Declaration | function greet() {} |
Function Expression | const greet = function() {} |
Arrow Function | const greet = () => {} |
Return Value | return something; |
Parameters/Arguments | function greet(name) {} |