JavaScript Functions
Write reusable logic with function patterns.
declarationarrow functionsreturn valuesTable of Contents
JavaScript Functions Tutorial (Beginner -> Advanced)
Functions are reusable blocks of code designed to perform a specific task. Instead of repeating the same logic, you define it once and call it whenever needed. This keeps your code clean, modular, and easier to maintain.
1. What is a Function?
A function is declared using the function keyword.
function greet() {
console.log("Hello, Welcome!");
}
greet(); // calling the functionWhen you call greet(), the code inside it executes.
2. Function with Parameters (Input)
Functions can take inputs called parameters.
function greet(name) {
console.log("Hello " + name);
}
greet("John");
greet("Priya");Here, name is a parameter, and values passed are arguments.
3. Function with Return Value (Output)
Functions can return results using return.
function add(a, b) {
return a + b;
}
let result = add(5, 3);
console.log(result);Once return executes, the function stops.
4. Function Expression
You can store a function inside a variable.
const multiply = function(a, b) {
return a * b;
};
console.log(multiply(4, 5));5. Arrow Functions (Modern JavaScript)
Short and cleaner syntax.
const add = (a, b) => {
return a + b;
};
// Short form (implicit return):
const square = x => x * x;6. Default Parameters
Set default values if no argument is passed.
function greet(name = "Guest") {
console.log("Hello " + name);
}
greet(); // Hello Guest7. Rest Parameters
Handle multiple arguments.
function sum(...numbers) {
let total = 0;
for (let num of numbers) {
total += num;
}
return total;
}
console.log(sum(1, 2, 3, 4));8. Callback Functions
A function passed as an argument to another function.
function greet(name, callback) {
console.log("Hello " + name);
callback();
}
function sayBye() {
console.log("Goodbye!");
}
greet("John", sayBye);9. Nested Functions
Functions inside other functions.
function outer() {
function inner() {
console.log("Inside inner function");
}
inner();
}
outer();10. Visual Understanding
Functions follow a simple flow: Input (arguments) -> Processing (function body) -> Output (return value). This mental model helps when debugging and designing reusable logic.
11. Real-Life Example
function calculateTotal(price, taxRate) {
return price + (price * taxRate);
}
let total = calculateTotal(100, 0.18);
console.log("Final Price:", total);12. Best Practices
- Use meaningful names like
calculateTotal()instead ofcalc(). - Keep functions small and focused on one task.
- Avoid unnecessary global variables inside functions.
- Use arrow functions for short logic and callbacks.
13. When to Use Functions
Functions are useful when you need to reuse code, organize logic, or break large problems into smaller steps. They are the foundation for advanced concepts like events, APIs, and frameworks.
Related Topics
Connect this topic with Loops, Arrays, and Asynchronous JavaScript to write reusable real-world logic.