Functions in JavaScript: Complete Guide with Examples
Functions in JavaScript:
Beginner to Advanced
Everything about JavaScript functions — declaration, expression, parameters, return values, default params, anonymous, callbacks, higher-order functions, scope, and best practices.
What is a Function in JavaScript?
A function is a reusable block of code that is designed to perform a specific task. Instead of writing the same code over and over in different places, you write it once inside a function, give it a name, and call (execute) it whenever you need it. Functions are the most important building block of JavaScript — every real program is built from functions.
Think of a function like a recipe. You write the recipe once (define the function). Whenever you want to cook that dish (call the function), you follow those steps. If you want to change how the dish is made, you update the recipe in one place and every version of the dish automatically improves.
Functions in JavaScript serve four key purposes: reusability (write once, use many times), organization (break complex code into manageable pieces), readability (named functions describe what they do), and maintainability (fix a bug in one place, not twenty).
Function Declaration — The Classic Way to Define a Function
A function declaration uses the function keyword followed by a name, parentheses for parameters, and curly braces for the body. This is the most traditional and readable way to define a function. An important feature of function declarations is hoisting — you can call them before they appear in your code.
// Function declaration — can be called before definition (hoisted) greetUser("Sara"); // ✅ Works even before the function definition! function greetUser(name) { console.log("Hello, " + name + "! ๐"); } // Function with multiple parameters function addNumbers(a, b) { return a + b; } console.log(addNumbers(5, 3)); // 8 console.log(addNumbers(20, 15)); // 35 // Function with no parameters function showTime() { let now = new Date(); console.log("Current time: " + now.toLocaleTimeString()); } showTime();
Hello, Sara! ๐
8 35
Current time: 10:45:32 AMFunction Expression, Parameters, Arguments & Return Statement
A function expression stores a function inside a variable. Unlike declarations, expressions are not hoisted — you must define them before calling them. Parameters are the variable names in the function definition; arguments are the actual values you pass when calling it. The return statement sends a value back to where the function was called.
// Function Expression — stored in a variable const multiply = function(a, b) { return a * b; // return sends result back }; console.log(multiply(4, 5)); // 20 // Parameters vs Arguments explained function getFullName(firstName, lastName) { // ← parameters return firstName + " " + lastName; } let result = getFullName("Ahmed", "Khan"); // ← arguments console.log(result); // Ahmed Khan // Return stops execution — code after return never runs function checkAge(age) { if (age < 0) return "Invalid age"; if (age >= 18) return "Adult ✅"; return "Minor ๐ง"; } console.log(checkAge(-1)); // Invalid age console.log(checkAge(20)); // Adult ✅ console.log(checkAge(15)); // Minor ๐ง
20
Ahmed Khan
Invalid age Adult ✅ Minor ๐งDefault Parameters & Anonymous Functions
Default parameters (introduced in ES6) allow you to specify fallback values for parameters that are not provided when the function is called. This eliminates the need for manual checks and makes your functions much more robust and flexible.
Anonymous functions are functions without a name. They are created on the spot and typically used as values — passed into other functions, stored in variables, or used immediately. They are the foundation of callbacks and event listeners.
// Default parameters — fallback if no argument passed function greet(name = "Guest", greeting = "Hello") { console.log(`${greeting}, ${name}! ๐`); } greet("Sara", "Hi"); // Hi, Sara! ๐ greet("Ali"); // Hello, Ali! ๐ (uses default greeting) greet(); // Hello, Guest! ๐ (uses both defaults) // Default with expression function createUser(name, role = "user", active = true) { return { name, role, active }; } console.log(createUser("Sara")); // { name: "Sara", role: "user", active: true } // Anonymous function — stored in a variable const square = function(n) { return n * n; }; console.log(square(7)); // 49 // Anonymous function used immediately (IIFE) (function() { console.log("I run immediately! ๐"); })();
Hi, Sara! ๐
Hello, Ali! ๐
Hello, Guest! ๐
{ name: "Sara", role: "user", active: true }
49
I run immediately! ๐Callback Functions & Higher-Order Functions
A callback function is a function that is passed as an argument to another function and called (executed) later — either immediately or after some event or operation completes. Callbacks are the foundation of asynchronous JavaScript and are used constantly in event listeners, array methods, and timers.
A higher-order function is a function that either takes another function as an argument, returns a function, or both. Higher-order functions are what make JavaScript so powerful and flexible. Built-in examples include .map(), .filter(), .forEach(), and .reduce().
// Callback — function passed as argument function processData(data, callback) { console.log("Processing: " + data); callback(data); } function printResult(result) { console.log("Result: " + result.toUpperCase()); } processData("hello world", printResult); // Processing: hello world // Result: HELLO WORLD // Higher-order functions — built-in array HOFs const numbers = [1, 2, 3, 4, 5, 6]; // map — transform every item const doubled = numbers.map(n => n * 2); console.log(doubled); // [2, 4, 6, 8, 10, 12] // filter — keep only matching items const evens = numbers.filter(n => n % 2 === 0); console.log(evens); // [2, 4, 6] // forEach — run code for every item numbers.forEach(n => console.log(`Item: ${n}`)); // Function that RETURNS a function function multiplier(factor) { return function(number) { return number * factor; }; } const triple = multiplier(3); const tenTimes = multiplier(10); console.log(triple(5)); // 15 console.log(tenTimes(4)); // 40
Processing: hello world
Result: HELLO WORLD
[2, 4, 6, 8, 10, 12]
[2, 4, 6]
Item: 1 Item: 2 ...
15 40Scope Inside Functions — What Variables Can You Access?
Scope inside functions determines which variables a function can access and which it cannot. JavaScript uses lexical scoping — a function can access variables from its own scope AND from any outer (parent) scope. But variables defined inside a function are not accessible outside it.
let globalVar = "I am global"; // accessible everywhere function outerFunction() { let outerVar = "I am outer"; function innerFunction() { let innerVar = "I am inner"; // innerFunction can see ALL levels console.log(globalVar); // ✅ I am global console.log(outerVar); // ✅ I am outer console.log(innerVar); // ✅ I am inner } innerFunction(); // console.log(innerVar); ← ReferenceError — inner scope ✅ } outerFunction(); // console.log(outerVar); ← ReferenceError — outer scope ✅ // Closure — function remembers its outer scope function makeCounter() { let count = 0; return function() { count++; console.log("Count: " + count); }; } const counter = makeCounter(); counter(); // Count: 1 counter(); // Count: 2 counter(); // Count: 3 — remembers count!
I am global I am outer I am inner
Count: 1 Count: 2 Count: 3count is remembered between calls.Function Best Practices — Write Code Like a Professional
Following best practices when writing functions will make your code dramatically more readable, maintainable, and professional. Here are the most important rules that senior developers follow:
✅ Use descriptive names —
getUserAge() not getUA() or func1()✅ Keep functions short — ideally under 20 lines. Shorter = easier to test and debug
✅ Always use return when a function produces a result — don't use console.log inside
✅ Use default parameters instead of checking for undefined inside the function
✅ Avoid global variables — declare variables inside functions to prevent conflicts
✅ Use arrow functions for short, simple callbacks —
arr.map(x => x * 2)✅ Document complex functions with a short comment explaining what they do
// ❌ Bad — does too many things, unclear name function doStuff(x) { console.log(x * 2); console.log(x + 10); console.log(x.toString()); } // ✅ Good — one job, clear name, returns value function doubleNumber(num) { return num * 2; } function addTen(num) { return num + 10; } // ✅ Arrow function for short callbacks const scores = [45, 78, 92, 60]; const passed = scores.filter(score => score >= 50); const names = ["sara", "ali", "ahmed"]; const upper = names.map(name => name.toUpperCase()); console.log(passed); // [78, 92, 60] console.log(upper); // ["SARA", "ALI", "AHMED"]
[78, 92, 60]
["SARA", "ALI", "AHMED"]✅ Complete Summary — Functions in JavaScript
๐ต Function Expression: const fn = function() {} — not hoisted, stored in variable
๐ก Parameters & Arguments: inputs to a function — default values prevent undefined errors
๐ Return Statement: sends result back to caller — stops function execution immediately
๐ฉท Anonymous Functions: no name — used as values, callbacks, or IIFE patterns
๐ฃ Callbacks & HOF: functions passed to/returned from other functions — map, filter, forEach
๐ฎ Scope & Closures: inner functions access outer scope — closures remember variables
⭐ Best Practice: One function = one job. Clear names. Short bodies. Always return values.
Functions are the most important concept in all of JavaScript. Every major concept you learn after this — async/await, React components, Node.js modules — is built on functions. Invest extra time practicing them. Write 5 different functions every day for a week and you will gain the confidence that makes everything else feel easy!
๐ป for more posts
- ๐ history of JavaScript
- ๐ variables in JavaScript
- ๐ data types in JavaScript
- ๐ arrays in JavaScript
- ๐ Conditional statements in JavaScript
- ๐ objects in JavaScript
- ๐ loops in JavaScript
- ๐ operators in JavaScript
- ๐ DOM Manipulation in JavaScript
- ๐ What is DOM in JavaScript
- ๐ JavaScript scope and hoisting
Comments
Post a Comment