Functions in JavaScript
Functions are one of the most important building blocks in JavaScript.
They let you group reusable code into blocks, execute tasks, and return results.
📜 What is a Function?
A function in JavaScript is a block of code designed to perform a specific task.
It is executed when "called" (invoked).
📌 Syntax
function functionName(parameters) {
// code to be executed
}
🧩 Types of Functions in JavaScript
1️⃣ Function Declaration (Named Function)
Defined using the function keyword.
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("Alice")); // Hello, Alice!
2️⃣ Function Expression
Stored in a variable.
const greet = function(name) {
return `Hello, ${name}!`;
};
console.log(greet("Bob"));
3️⃣ Arrow Function (ES6)
Shorter syntax for functions.
const greet = (name) => `Hello, ${name}!`;
console.log(greet("Charlie"));
4️⃣ Anonymous Function
A function without a name, often used in callbacks.
setTimeout(function() {
console.log("This runs after 2 seconds");
}, 2000);
5️⃣ Immediately Invoked Function Expression (IIFE)
Executes immediately after creation.
(function() {
console.log("I run immediately!");
})();
📥 Function Parameters & Arguments
- Parameters: Variables listed in the function definition.
- Arguments: Values passed when calling the function.
function sum(a, b) {
return a + b;
}
console.log(sum(5, 3)); // 8
🔄 Default Parameters
Assign default values if no argument is passed.
function greet(name = "Guest") {
console.log(`Hello, ${name}!`);
}
greet(); // Hello, Guest!
♻ Return Statement
Functions can return values using return.
function multiply(a, b) {
return a * b;
}
let result = multiply(4, 5);
console.log(result); // 20
🧠 Function Scope
Variables inside a function are local and can’t be accessed outside.
function test() {
let x = 10;
console.log(x); // 10
}
console.log(x); // ❌ Error: x is not defined
🏗 Higher-Order Functions
Functions that take other functions as arguments or return them.
function operate(a, b, operation) {
return operation(a, b);
}
console.log(operate(5, 3, (x, y) => x + y)); // 8
⏳ Callback Functions
A function is passed as an argument to another function.
function fetchData(callback) {
console.log("Fetching data...");
callback();
}
fetchData(() => console.log("Data fetched!"));
📚 Best Practices
- ✅ Use meaningful function names
- ✅ Keep functions short & focused
- ✅ Use arrow functions for concise code
- ✅ Avoid global variables inside functions
- ✅ Document parameters & return values
📌 Summary
Functions in JavaScript
- 🚀 Make code reusable
- 📦 Accept inputs (parameters) and return outputs
- 🔄 Can be declared in multiple ways (declaration, expression, arrow)
- 🧠 Support advanced concepts like callbacks and higher-order functions