Functions in JavaScript
Functions are one of the most important building blocks in JavaScript. They allow you to organize code into reusable blocks that perform a specific task. Understanding functions well will make your code cleaner, easier to maintain, and more efficient.
1. What is a Function?
A function is a block of code designed to perform a particular task. Instead of writing the same code multiple times, you can define a function once and call it whenever needed.
Syntax:
function functionName(parameters) {
// Code to execute
return value; // optional
}
Example:
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Kavitha"); // Output: Hello, Kavitha!
2. Components of a Function
- Function Name – The identifier used to call the function.
- Parameters – Input values passed to the function (optional).
- Function Body – The code block that runs when the function is called.
- Return Statement – Sends a value back to the caller (optional).
Example:
function add(a, b) {
return a + b; // Returns the sum of a and b
}
let result = add(5, 3);
console.log(result); // Output: 8
3. Types of Functions
a) Function Declaration
function sayHello() {
console.log("Hello World!");
}
sayHello();
- Hoisted in JavaScript → Can be called before declaration.
- Classic way of defining functions.
b) Function Expression
const multiply = function(x, y) {
return x * y;
};
console.log(multiply(4, 5)); // Output: 20
- Not hoisted → Must be defined before calling.
- Can be anonymous or named.
c) Arrow Functions
const divide = (a, b) => a / b;
console.log(divide(10, 2)); // Output: 5
- Shorter syntax.
- No
thisbinding → Useful in modern JS like React or Node.js.
4. Functions with Default Parameters
You can set default values for parameters in case no value is passed:
function greet(name = "Guest") {
console.log("Hello, " + name + "!");
}
greet(); // Output: Hello, Guest!
greet("Kavitha"); // Output: Hello, Kavitha!
5. Functions Returning Values
A function can return a value to be used elsewhere:
function square(number) {
return number * number;
}
let result = square(6);
console.log(result); // Output: 36
6. Why Use Functions?
- Reusability: Write once, use multiple times.
- Maintainability: Easy to update logic in one place.
- Modularity: Break code into smaller, manageable parts.
- Readability: Makes code cleaner and easier to understand.
7. Best Practices
- Give functions meaningful names:
calculateSuminstead ofdoStuff. - Keep functions small and focused on one task.
- Avoid side effects when possible → Functions should ideally only use inputs and return outputs.
- Use arrow functions for concise syntax when appropriate.

Top comments (0)