JavaScript Functions
Learn how to create reusable blocks of code using function declarations, function expressions, parameters, arguments, return values, arrow functions, callbacks, recursion, and practical function patterns.
Introduction
As programs grow, the same logic often needs to be used in multiple places. Repeating the same code makes programs longer, harder to understand, and more difficult to maintain.
JavaScript solves this problem with functions. A function groups instructions into a reusable block of code that can be executed whenever needed.
Functions can receive input, process data, perform actions, and return results. They allow large programs to be divided into smaller and more manageable pieces.
Functions are one of the most important concepts in JavaScript. Events, array methods, asynchronous programming, modules, frameworks, APIs, and modern application development all depend heavily on functions.
- What functions are and why they are needed.
- How functions are created and executed.
- The difference between declaring and calling a function.
- How parameters work.
- How arguments work.
- The difference between parameters and arguments.
- How to use multiple parameters.
- What happens when arguments are missing.
- How default parameters work.
- How the return statement works.
- How to use returned values.
- Why return stops function execution.
- How function declarations work.
- How function expressions work.
- What anonymous functions are.
- How arrow functions work.
- How implicit return works.
- How functions can be stored in variables.
- How functions can be passed to other functions.
- What callback functions are.
- What higher-order functions are.
- How functions can return other functions.
- How rest parameters work.
- What pure and impure functions are.
- What side effects are.
- How recursive functions work.
- How to create reusable utility functions.
- How functions are used in real applications.
What is a Function?
A function is a reusable block of code designed to perform a specific task. The function is defined once and can be executed whenever required.
function greet() {
console.log('Hello!');
}
greet();DEFINE FUNCTION
│
▼
┌─────────────────┐
│ function greet │
│ │
│ Print "Hello!" │
└─────────────────┘
│
│ Function waits
│ until called
▼
greet()
│
▼
Execute Code
│
▼
Hello!- A function stores reusable instructions.
- A function performs a specific task.
- A function runs when it is called.
- A function can receive input.
- A function can return output.
Why Do We Need Functions?
Functions prevent code duplication and allow complex programs to be divided into smaller logical units.
Reusability
Write logic once and execute it many times.
Modularity
Divide large programs into smaller independent tasks.
Readability
Descriptive function names make program logic easier to understand.
Maintainability
Update logic in one function instead of changing duplicate code everywhere.
Testing
Small functions are easier to test individually.
Debugging
Problems are easier to locate when logic is divided into focused functions.
const price1 = 100;
const tax1 = price1 * 0.18;
console.log(price1 + tax1);
const price2 = 500;
const tax2 = price2 * 0.18;
console.log(price2 + tax2);
const price3 = 1000;
const tax3 = price3 * 0.18;
console.log(price3 + tax3);function calculateTotal(price) {
const tax = price * 0.18;
return price + tax;
}
console.log(calculateTotal(100));
console.log(calculateTotal(500));
console.log(calculateTotal(1000));Real-World Analogy
Imagine a coffee machine. You provide input, the machine performs a predefined process, and it produces an output.
INPUT
Coffee Type
Sugar Level
Milk Option
│
▼
┌──────────────────┐
│ COFFEE MACHINE │
│ │
│ Grind Beans │
│ Heat Water │
│ Mix Ingredients │
└────────┬─────────┘
│
▼
OUTPUT
Prepared CoffeeA function works similarly. Arguments provide input, the function body performs processing, and the return statement can produce an output.
function makeCoffee(type, sugar) {
return `${type} coffee with ${sugar} sugar`;
}
const coffee = makeCoffee('Cold', 2);
console.log(coffee);How Functions Work
A function normally follows three stages: definition, call, and execution.
1. DEFINE FUNCTION
│
▼
function greet() {
console.log('Hello');
}
│
▼
2. CALL FUNCTION
│
▼
greet()
│
▼
3. EXECUTE BODY
│
▼
Hellofunction showMessage() {
console.log('Function is running.');
}
console.log('Before function');
showMessage();
console.log('After function');Function Terminology
Term Meaning
--------------------------------------------------
Function Reusable block of code
Declaration Creates a function
Function Name Identifier used to call it
Parameter Input variable in definition
Argument Actual value passed to function
Function Body Code inside { }
Function Call Executes the function
Return Value Result sent back by function
Callback Function passed to another function
Higher-Order Function that receives or returns
Function another function
Recursion Function calling itselfFunction Declaration
A function declaration creates a named function using the function keyword.
function sayHello() {
console.log('Hello, JavaScript!');
}
sayHello();Function Syntax
function functionName(parameters) {
// Function body
}function calculateTotal(price, tax) {
│ │ │
│ │ └── Parameters
│ │
│ └───────────── Function Name
│
└──────────────────────── function Keyword
{
return price + tax;
}
│
└── Function Body- Function names follow JavaScript identifier rules.
- Names cannot begin with a number.
- Reserved keywords cannot be used as function names.
- Names are case-sensitive.
- Use descriptive action-based names.
- camelCase is commonly used.
Calling a Function
Creating a function does not automatically execute its body. The function must be called using its name followed by parentheses.
function displayWelcome() {
console.log('Welcome to PrograMinds!');
}
// Function call
displayWelcome();function displayWelcome() {
console.log('Welcome!');
}
// No function call
console.log('Program finished.');Function Execution Flow
console.log('Step 1');
function greet() {
console.log('Step 2');
console.log('Step 3');
}
greet();
console.log('Step 4');START
│
▼
Print Step 1
│
▼
Call greet()
│
├───────────────┐
│ ▼
│ Enter Function
│ │
│ ▼
│ Print Step 2
│ │
│ ▼
│ Print Step 3
│ │
│ ▼
│ Function Ends
│ │
◄───────────────┘
│
▼
Print Step 4
│
▼
ENDCalling a Function Multiple Times
A function can be called as many times as required. Every call executes the function body again.
function showMessage() {
console.log('Learning JavaScript!');
}
showMessage();
showMessage();
showMessage();Parameters
Parameters are variables listed in a function definition. They allow a function to receive input.
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet('Aarav');FUNCTION DEFINITION
function greet(name)
│
└── Parameter
FUNCTION CALL
greet('Aarav')
│
└── Value enters name
INSIDE FUNCTION
name = 'Aarav'Arguments
Arguments are the actual values supplied when a function is called.
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet('Priya');
greet('Rohan');
greet('Amit');Parameters vs Arguments
Feature Parameter Argument
----------------------------------------------------------
Location Function definition Function call
Purpose Receives data Supplies data
Example name 'Rahul'
function greet(name) {
└── Parameter
}
greet('Rahul');
└── ArgumentMultiple Parameters
A function can receive multiple parameters. Parameters are separated by commas.
function introduce(name, age, city) {
console.log(
`${name} is ${age} years old and lives in ${city}.`
);
}
introduce('Rahul', 25, 'Mumbai');- Arguments are matched with parameters by position.
- The first argument goes to the first parameter.
- The second argument goes to the second parameter.
- Passing values in the wrong order may produce incorrect results.
Missing Arguments
When a function is called with fewer arguments than parameters, the missing parameters receive the value undefined.
function introduce(name, age) {
console.log('Name:', name);
console.log('Age:', age);
}
introduce('Priya');Default Parameters
Default parameters provide fallback values when an argument is missing or explicitly passed as undefined.
function greet(name = 'Guest') {
console.log(`Hello, ${name}!`);
}
greet('Aarav');
greet();function createUser(
name = 'Unknown',
role = 'User',
active = true
) {
console.log(name, role, active);
}
createUser();
createUser('Amit', 'Admin');The return Statement
The return statement sends a value back to the location where the function was called.
function add(a, b) {
return a + b;
}
const result = add(10, 20);
console.log(result);add(10, 20)
│
▼
┌─────────────────┐
│ a = 10 │
│ b = 20 │
│ │
│ return a + b │
└────────┬────────┘
│
▼
30
│
▼
result = 30Returning Values
A function can return numbers, strings, booleans, arrays, objects, functions, and other JavaScript values.
function getNumber() {
return 100;
}
function getMessage() {
return 'Hello';
}
function isAdult(age) {
return age >= 18;
}
console.log(getNumber());
console.log(getMessage());
console.log(isAdult(25));Using Returned Values
A returned value can be stored, displayed, passed to another function, or used in another expression.
function multiply(a, b) {
return a * b;
}
const result = multiply(5, 4);
console.log(result);function square(number) {
return number * number;
}
const total = square(5) + square(3);
console.log(total);return Stops Function Execution
When JavaScript reaches a return statement, the function immediately stops executing.
function test() {
console.log('Before return');
return;
console.log('After return');
}
test();- Code after an unconditional return statement does not execute.
- return immediately exits the current function.
- Avoid placing necessary logic after return.
Multiple Return Statements
A function can contain multiple return statements. Usually, conditions determine which return statement executes.
function getAgeCategory(age) {
if (age < 0) {
return 'Invalid Age';
}
if (age < 13) {
return 'Child';
}
if (age < 18) {
return 'Teenager';
}
return 'Adult';
}
console.log(getAgeCategory(10));
console.log(getAgeCategory(16));
console.log(getAgeCategory(25));Function Without return
A function that does not explicitly return a value automatically returns undefined.
function showMessage() {
console.log('Hello');
}
const result = showMessage();
console.log(result);Function Declaration vs Function Call
Function Declaration
function greet() {
console.log('Hello');
}
Purpose:
Creates the function
Function Call
greet();
Purpose:
Executes the functionFunction Expressions
A function expression creates a function and stores it in a variable.
const greet = function () {
console.log('Hello!');
};
greet();const add = function (a, b) {
return a + b;
};
console.log(add(10, 20));Anonymous Functions
An anonymous function is a function without its own name. Anonymous functions are commonly stored in variables or passed to other functions.
const multiply = function (a, b) {
return a * b;
};
console.log(multiply(5, 6));Named Function Expressions
A function expression can also contain an internal function name.
const calculate = function addNumbers(a, b) {
return a + b;
};
console.log(calculate(10, 15));Function Declaration vs Function Expression
Feature Declaration Expression
--------------------------------------------------------
Syntax function name() const name =
function()
Stored in variable Not required Yes
Can be anonymous No Yes
Common use Reusable named Values,
functions callbacks
Hoisting behavior Fully available Depends on
earlier variableArrow Functions
Arrow functions provide a shorter syntax for writing function expressions. They were introduced in ES6.
const add = function (a, b) {
return a + b;
};const add = (a, b) => {
return a + b;
};
console.log(add(10, 20));Arrow Function Syntax
const functionName = (parameters) => {
// Function body
};const add = (a, b) => {
│ │ │
│ │ └── Arrow
│ │
│ └───────── Parameters
│
└───────────────── Variable NameArrow Function with a Single Parameter
Parentheses can be omitted when an arrow function has exactly one simple parameter.
const square = number => {
return number * number;
};
console.log(square(5));Arrow Function with Multiple Parameters
Parentheses are required when an arrow function has multiple parameters.
const multiply = (a, b) => {
return a * b;
};
console.log(multiply(4, 5));Implicit Return
When an arrow function contains a single expression, braces and the return keyword can be omitted.
const add = (a, b) => {
return a + b;
};const add = (a, b) => a + b;
console.log(add(10, 20));Returning Objects from Arrow Functions
To implicitly return an object literal from an arrow function, wrap the object in parentheses.
const createUser = (name, age) => ({
name: name,
age: age
});
console.log(createUser('Amit', 25));Traditional vs Arrow Functions
Feature Traditional Arrow
--------------------------------------------------------
Syntax Longer Shorter
function keyword Required Not used
=> operator Not used Required
Implicit return No Yes
Own arguments Yes No
Own this behavior Yes No
Common use Methods, general Callbacks,
functions short functions- Arrow functions do not have their own this binding.
- Arrow functions do not have their own arguments object.
- Arrow functions cannot be used as constructors with new.
- Choose the function type based on behavior, not only shorter syntax.
Functions as Values
In JavaScript, functions are values. They can be stored in variables, placed in objects, passed to other functions, and returned from functions.
function greet() {
return 'Hello!';
}
const anotherFunction = greet;
console.log(anotherFunction());- Functions can be assigned to variables.
- Functions can be passed as arguments.
- Functions can be returned from other functions.
- Functions can be stored in data structures.
Passing Functions to Other Functions
function sayHello() {
console.log('Hello!');
}
function executeFunction(callback) {
callback();
}
executeFunction(sayHello);sayHello
│
▼
Passed to executeFunction
│
▼
Stored as callback
│
▼
callback()
│
▼
sayHello executes
│
▼
Hello!Callback Functions
A callback is a function passed to another function so that it can be executed later or at a specific point in the operation.
function processUser(name, callback) {
console.log(`Processing ${name}...`);
callback(name);
}
function showWelcome(name) {
console.log(`Welcome, ${name}!`);
}
processUser('Priya', showWelcome);Synchronous Callbacks
A synchronous callback executes immediately during the execution of another function.
function calculate(a, b, operation) {
return operation(a, b);
}
function add(a, b) {
return a + b;
}
function multiply(a, b) {
return a * b;
}
console.log(calculate(10, 5, add));
console.log(calculate(10, 5, multiply));Callbacks with Events
Browser events commonly use callback functions. The callback executes when the event occurs.
<button id="welcomeButton">
Show Welcome Message
</button>
<p id="message"></p>const button =
document.getElementById('welcomeButton');
const message =
document.getElementById('message');
function showWelcome() {
message.textContent =
'Welcome to JavaScript Functions!';
}
button.addEventListener(
'click',
showWelcome
);Higher-Order Functions
A higher-order function is a function that receives another function as an argument, returns a function, or does both.
function repeat(count, action) {
for (let i = 1; i <= count; i++) {
action(i);
}
}
repeat(3, function (number) {
console.log(`Execution ${number}`);
});Functions Returning Functions
Because functions are values, one function can create and return another function.
function createMultiplier(multiplier) {
return function (number) {
return number * multiplier;
};
}
const double = createMultiplier(2);
const triple = createMultiplier(3);
console.log(double(5));
console.log(triple(5));createMultiplier(2)
│
▼
multiplier = 2
│
▼
Return New Function
│
▼
double(number)
│
▼
number × 2Rest Parameters
A rest parameter collects multiple arguments into an array. It is written using three dots before the parameter name.
function sum(...numbers) {
let total = 0;
for (const number of numbers) {
total += number;
}
return total;
}
console.log(sum(10, 20));
console.log(sum(10, 20, 30, 40));function introduce(prefix, ...names) {
for (const name of names) {
console.log(`${prefix} ${name}`);
}
}
introduce(
'Hello',
'Aarav',
'Priya',
'Rohan'
);The arguments Object
Traditional functions have access to an array-like arguments object containing the values passed during the function call.
function showArguments() {
console.log(arguments[0]);
console.log(arguments[1]);
console.log(arguments.length);
}
showArguments('JavaScript', 1995);- Rest parameters create a real array.
- Rest parameters are clearer and more modern.
- Arrow functions do not have their own arguments object.
- Use ...values when accepting a variable number of arguments.
Pure Functions
A pure function produces the same output for the same input and does not change data outside itself.
function add(a, b) {
return a + b;
}
console.log(add(10, 20));
console.log(add(10, 20));- Same input produces the same output.
- No external data is modified.
- No hidden dependency changes the result.
- They are easier to test and understand.
Impure Functions
An impure function depends on or modifies data outside itself, or performs observable external actions.
let total = 0;
function addToTotal(amount) {
total += amount;
}
addToTotal(100);
addToTotal(50);
console.log(total);Side Effects
A side effect occurs when a function changes something outside its local computation or interacts with the external environment.
Modifying Variables
Changing a variable declared outside the function.
Updating the DOM
Changing HTML content, attributes, or styles.
Storage
Writing data to local storage or session storage.
Network Requests
Sending or receiving data through an API.
Console Output
Writing information to the browser console.
File Operations
Reading or writing external files in supported environments.
Recursive Functions
Recursion occurs when a function calls itself to solve a smaller version of the same problem.
function countdown(number) {
if (number <= 0) {
console.log('Finished!');
return;
}
console.log(number);
countdown(number - 1);
}
countdown(5);countdown(3)
│
▼
Print 3
│
▼
countdown(2)
│
▼
Print 2
│
▼
countdown(1)
│
▼
Print 1
│
▼
countdown(0)
│
▼
FinishedThe Base Case
A recursive function needs a base case. The base case stops further recursive calls.
function countdown(number) {
// Base case
if (number <= 0) {
return;
}
console.log(number);
// Recursive call
countdown(number - 1);
}- Every recursive function needs a stopping condition.
- Without a base case, recursion continues indefinitely.
- Too many recursive calls can cause a stack overflow.
- Use recursion only when it makes the problem clearer.
Factorial with Recursion
function factorial(number) {
if (number <= 1) {
return 1;
}
return number * factorial(number - 1);
}
console.log(factorial(5));factorial(5)
5 × factorial(4)
│
▼
5 × 4 × factorial(3)
│
▼
5 × 4 × 3 × factorial(2)
│
▼
5 × 4 × 3 × 2 × factorial(1)
│
▼
5 × 4 × 3 × 2 × 1
= 120Function Composition
Function composition combines small functions so that the result of one function becomes the input of another.
function double(number) {
return number * 2;
}
function addTen(number) {
return number + 10;
}
const result = addTen(double(5));
console.log(result);Input: 5
│
▼
double(5)
│
▼
10
│
▼
addTen(10)
│
▼
20Reusable Utility Functions
Utility functions perform small reusable tasks that may be needed in many parts of an application.
function isEven(number) {
return number % 2 === 0;
}
function calculatePercentage(value, total) {
return (value / total) * 100;
}
function formatCurrency(amount) {
return `₹${amount.toFixed(2)}`;
}
console.log(isEven(10));
console.log(calculatePercentage(45, 50));
console.log(formatCurrency(1250));Temperature Converter
function celsiusToFahrenheit(celsius) {
return (celsius * 9 / 5) + 32;
}
function fahrenheitToCelsius(fahrenheit) {
return (fahrenheit - 32) * 5 / 9;
}
console.log(
celsiusToFahrenheit(30)
);
console.log(
fahrenheitToCelsius(86)
);Grade Calculator
function calculateGrade(marks) {
if (
marks < 0 ||
marks > 100
) {
return 'Invalid Marks';
}
if (marks >= 90) {
return 'A+';
}
if (marks >= 80) {
return 'A';
}
if (marks >= 70) {
return 'B';
}
if (marks >= 60) {
return 'C';
}
if (marks >= 40) {
return 'D';
}
return 'Fail';
}
console.log(calculateGrade(95));
console.log(calculateGrade(72));
console.log(calculateGrade(30));Complete Calculator
The following example uses separate reusable functions for calculator operations and a central function to choose the correct operation.
<div class="calculator">
<h2>Function Calculator</h2>
<input
type="number"
id="firstNumber"
placeholder="First number"
>
<select id="operator">
<option value="+">Add (+)</option>
<option value="-">Subtract (-)</option>
<option value="*">Multiply (×)</option>
<option value="/">Divide (÷)</option>
</select>
<input
type="number"
id="secondNumber"
placeholder="Second number"
>
<button id="calculateButton">
Calculate
</button>
<p id="result"></p>
</div>const firstNumberInput =
document.getElementById('firstNumber');
const secondNumberInput =
document.getElementById('secondNumber');
const operatorInput =
document.getElementById('operator');
const calculateButton =
document.getElementById('calculateButton');
const resultElement =
document.getElementById('result');
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
function multiply(a, b) {
return a * b;
}
function divide(a, b) {
if (b === 0) {
return 'Cannot divide by zero.';
}
return a / b;
}
function calculate(a, b, operator) {
switch (operator) {
case '+':
return add(a, b);
case '-':
return subtract(a, b);
case '*':
return multiply(a, b);
case '/':
return divide(a, b);
default:
return 'Invalid operator.';
}
}
calculateButton.addEventListener(
'click',
function () {
const firstNumber =
Number(firstNumberInput.value);
const secondNumber =
Number(secondNumberInput.value);
const operator =
operatorInput.value;
if (
Number.isNaN(firstNumber) ||
Number.isNaN(secondNumber)
) {
resultElement.textContent =
'Please enter valid numbers.';
return;
}
const result = calculate(
firstNumber,
secondNumber,
operator
);
resultElement.textContent =
`Result: ${result}`;
}
);Function Execution Model
┌───────────────────────┐
│ FUNCTION CREATED │
│ │
│ Name │
│ Parameters │
│ Function Body │
└───────────┬───────────┘
│
│ Wait for call
▼
┌───────────────────────┐
│ FUNCTION CALL │
│ │
│ Arguments supplied │
└───────────┬───────────┘
│
▼
┌───────────────────────┐
│ ARGUMENTS ASSIGNED TO │
│ PARAMETERS │
└───────────┬───────────┘
│
▼
┌───────────────────────┐
│ EXECUTE FUNCTION │
│ BODY │
└───────────┬───────────┘
│
▼
return reached?
│
┌────┴────┐
│ │
Yes No
│ │
▼ ▼
Return Value End Body
│ │
└────┬────┘
▼
┌───────────────────────┐
│ RETURN CONTROL TO THE │
│ CALLING CODE │
└───────────────────────┘Choosing the Right Function Type
Situation Recommended Style
------------------------------------------------------------
General reusable function Function declaration
Store function in variable Function expression
Short callback Arrow function
Single expression Arrow + implicit return
Need own this Traditional function
Need own arguments Traditional function
Variable number of inputs Rest parameter
Pass behavior to function Callback
Function accepts function Higher-order function
Function returns function Higher-order function
Self-repeating problem Recursive functionReal-World Applications
Form Validation
Create reusable functions to validate names, emails, passwords, and other input.
E-Commerce
Calculate totals, taxes, discounts, delivery charges, and prices.
User Interfaces
Handle buttons, menus, forms, modals, and other interactions.
Data Processing
Transform, filter, calculate, and analyze application data.
API Communication
Create functions for sending requests and processing responses.
Games
Create reusable logic for movement, scoring, collisions, and game states.
Authentication
Validate credentials, permissions, sessions, and access rules.
Application Architecture
Divide large applications into smaller reusable units of behavior.
Common Beginner Mistakes
- Creating a function but forgetting to call it.
- Calling a function with the wrong name.
- Forgetting parentheses when calling a function.
- Confusing function declaration with function execution.
- Confusing parameters with arguments.
- Passing arguments in the wrong order.
- Passing fewer arguments than expected.
- Assuming missing arguments automatically receive useful values.
- Forgetting to use default parameters when appropriate.
- Forgetting the return keyword.
- Expecting console.log() to return the displayed value.
- Writing necessary code after an unconditional return statement.
- Expecting a function without return to produce a useful result.
- Using return outside a function.
- Creating functions that perform too many unrelated tasks.
- Using unclear function names.
- Using nouns for functions that perform actions.
- Changing global variables unnecessarily.
- Creating unnecessary side effects.
- Using arrow functions without understanding their this behavior.
- Expecting arrow functions to have their own arguments object.
- Forgetting parentheses around an implicitly returned object.
- Calling a callback immediately instead of passing the function.
- Writing callback() when the function itself should be passed.
- Forgetting the base case in recursion.
- Creating recursion that never reaches the base case.
- Using recursion when a simple loop would be clearer.
- Using too many parameters.
- Modifying parameter values unnecessarily.
- Duplicating logic instead of creating a reusable function.
- Creating extremely long functions.
- Using generic names such as doStuff or processData without context.
- Mixing input, processing, and output unnecessarily.
- Ignoring invalid input.
- Returning inconsistent data types without a clear reason.
- Overusing anonymous functions when a named function would improve readability.
// ❌ Function is never called
function greet() {
console.log('Hello');
}
// ❌ Missing return
function add(a, b) {
a + b;
}
// ❌ Code after return never executes
function test() {
return 'Done';
console.log('Never runs');
}
// ❌ Passing result instead of callback
// executeFunction(sayHello());
// ❌ Missing recursion base case
// function countdown(number) {
// console.log(number);
// countdown(number - 1);
// }
// ❌ Too many unrelated responsibilities
function processEverything() {
// Validate form
// Calculate price
// Update DOM
// Save storage
// Send API request
}Best Practices
- Give functions descriptive names.
- Use action-based names such as calculateTotal, validateEmail, and showMessage.
- Keep each function focused on one main responsibility.
- Avoid extremely long functions.
- Extract repeated logic into reusable functions.
- Use parameters instead of depending unnecessarily on global variables.
- Use return values to make functions reusable.
- Validate important function inputs.
- Use default parameters when sensible fallback values exist.
- Keep the number of parameters manageable.
- Consider an object parameter when many related values are required.
- Use const when storing function expressions that will not be reassigned.
- Prefer function declarations for clear reusable named operations.
- Use arrow functions for short callbacks when their behavior is appropriate.
- Do not use arrow functions only because they are shorter.
- Understand this before replacing traditional functions with arrows.
- Use explicit return when it improves readability.
- Use implicit return for simple expressions.
- Wrap object literals in parentheses when using implicit return.
- Pass function references when callbacks are required.
- Use descriptive callback names for complex behavior.
- Keep callback nesting manageable.
- Use rest parameters instead of the arguments object in modern code.
- Prefer pure functions for calculations and transformations when possible.
- Keep side effects intentional and easy to identify.
- Avoid modifying global state unnecessarily.
- Always provide a base case for recursive functions.
- Make sure recursion moves toward the base case.
- Prefer a simple loop when recursion makes the code harder to understand.
- Return consistent types when possible.
- Document unusual function behavior.
- Test functions with normal input.
- Test functions with boundary values.
- Test functions with missing input.
- Test functions with invalid input.
- Build small reusable utility functions for repeated operations.
- Prefer readable code over clever one-line functions.
function calculateDiscount(
price,
discountPercentage = 0
) {
if (
typeof price !== 'number' ||
typeof discountPercentage !== 'number'
) {
return null;
}
if (
price < 0 ||
discountPercentage < 0 ||
discountPercentage > 100
) {
return null;
}
const discountAmount =
price * (discountPercentage / 100);
return price - discountAmount;
}
const finalPrice =
calculateDiscount(1000, 20);
if (finalPrice === null) {
console.log('Invalid input.');
} else {
console.log(
`Final Price: ₹${finalPrice}`
);
}Frequently Asked Questions
What is a function?
A function is a reusable block of code designed to perform a specific task.
Why are functions useful?
Functions reduce duplicate code, improve organization, increase reusability, and make programs easier to maintain.
Does defining a function execute it?
No. A function normally executes only when it is called.
How do I call a function?
Write the function name followed by parentheses, such as greet().
Can a function be called multiple times?
Yes. A function can be called as many times as required.
What is a parameter?
A parameter is a variable listed in the function definition that receives input.
What is an argument?
An argument is an actual value supplied when calling a function.
What is the difference between a parameter and an argument?
A parameter appears in the function definition, while an argument is supplied during the function call.
Can a function have multiple parameters?
Yes. Multiple parameters are separated by commas.
Does argument order matter?
Yes. Arguments are normally matched with parameters by position.
What happens when an argument is missing?
The corresponding parameter receives undefined unless it has a default value.
What is a default parameter?
A default parameter provides a fallback value when an argument is missing or undefined.
What does return do?
return sends a value back to the caller and immediately stops the current function.
Can a function return multiple values?
A function directly returns one value, but that value can be an array or object containing multiple pieces of data.
What does a function return without return?
It returns undefined.
Does code after return execute?
No. An unconditional return immediately ends function execution.
Can a function have multiple return statements?
Yes. Conditions can determine which return statement executes.
What is a function expression?
A function expression creates a function as a value and usually stores it in a variable.
What is an anonymous function?
An anonymous function is a function without its own name.
What is an arrow function?
An arrow function is a shorter syntax for creating function expressions.
When can parentheses be removed from an arrow function?
They can be removed when there is exactly one simple parameter.
What is implicit return?
An arrow function with a single expression can return that expression without braces or the return keyword.
How do I implicitly return an object?
Wrap the object literal in parentheses.
Are arrow functions the same as traditional functions?
No. They differ in important behaviors including this, arguments, and constructor usage.
What does it mean that functions are values?
Functions can be stored in variables, passed as arguments, and returned from other functions.
What is a callback function?
A callback is a function passed to another function for execution.
What is a higher-order function?
A higher-order function receives another function, returns another function, or both.
Can a function return another function?
Yes. Functions are values and can be returned like other values.
What is a rest parameter?
A rest parameter collects remaining arguments into an array using ... before the parameter name.
What is the arguments object?
It is an array-like object available inside traditional functions containing supplied arguments.
Do arrow functions have arguments?
Arrow functions do not have their own arguments object.
What is a pure function?
A pure function produces the same output for the same input and does not create external side effects.
What is an impure function?
An impure function depends on changing external state or creates observable side effects.
What is a side effect?
A side effect is an observable change outside the function result, such as updating the DOM or modifying external state.
What is recursion?
Recursion occurs when a function calls itself.
What is a base case?
A base case is the stopping condition that prevents recursive calls from continuing forever.
Can recursion cause errors?
Yes. Excessive or infinite recursion can cause a stack overflow.
What is function composition?
Function composition combines functions so that the result of one becomes the input of another.
How long should a function be?
There is no fixed limit, but a function should remain focused, understandable, and responsible for one main task.
Which function type should I use?
Choose based on behavior and readability. Use declarations for clear reusable functions, expressions when treating functions as values, and arrow functions for suitable concise callbacks.
Key Takeaways
- Functions are reusable blocks of code.
- Functions help reduce code duplication.
- Functions divide large programs into smaller tasks.
- A function declaration uses the function keyword.
- A function must normally be called before its body executes.
- A function can be called multiple times.
- Parameters receive input inside a function.
- Arguments provide actual values during a function call.
- Parameters and arguments are different concepts.
- A function can have multiple parameters.
- Argument order normally matters.
- Missing arguments produce undefined unless defaults are provided.
- Default parameters provide fallback values.
- return sends a value back to the caller.
- return immediately stops function execution.
- A function without an explicit return returns undefined.
- A function can contain multiple conditional return statements.
- Function expressions store functions as values.
- Anonymous functions do not have their own names.
- Arrow functions provide shorter function expression syntax.
- Single-expression arrow functions can use implicit return.
- Object literals need parentheses for implicit return.
- Arrow functions differ from traditional functions.
- Functions are first-class values in JavaScript.
- Functions can be assigned to variables.
- Functions can be passed as arguments.
- Functions can be returned from other functions.
- Callbacks are functions passed to other functions.
- Higher-order functions receive or return functions.
- Rest parameters collect multiple arguments into an array.
- Traditional functions have an arguments object.
- Arrow functions do not have their own arguments object.
- Pure functions avoid external side effects.
- Impure functions interact with or modify external state.
- Recursion occurs when a function calls itself.
- Recursive functions need a base case.
- Function composition combines small reusable functions.
- Utility functions perform reusable application tasks.
- Functions are fundamental to modern JavaScript development.
Summary
Functions allow JavaScript programs to organize logic into reusable blocks. A function can be defined once and executed whenever required.
Parameters allow functions to receive input, while arguments provide the actual values. Default parameters can provide fallback values when arguments are missing.
The return statement sends a result back to the caller and immediately ends function execution. Returned values can be stored, displayed, passed to other functions, or used in expressions.
JavaScript supports function declarations, function expressions, anonymous functions, and arrow functions. Each style is useful in different situations.
Because functions are first-class values, they can be stored in variables, passed as callbacks, and returned from higher-order functions.
Pure functions, side effects, recursion, function composition, and reusable utility functions are important concepts for writing structured and maintainable JavaScript applications.
- You understand what functions are.
- You understand why functions are needed.
- You can declare and call functions.
- You understand function execution flow.
- You can use parameters.
- You can pass arguments.
- You understand parameters versus arguments.
- You can use multiple parameters.
- You understand missing arguments.
- You can use default parameters.
- You can return values.
- You understand that return stops execution.
- You can use multiple return statements.
- You understand functions without return.
- You can create function expressions.
- You understand anonymous functions.
- You can create arrow functions.
- You can use implicit return.
- You can return objects from arrow functions.
- You understand functions as values.
- You can pass functions to other functions.
- You understand callbacks.
- You understand higher-order functions.
- You can return functions from functions.
- You can use rest parameters.
- You understand the arguments object.
- You understand pure and impure functions.
- You understand side effects.
- You understand recursion.
- You understand the importance of a base case.
- You can create reusable utility functions.
- You are ready to learn JavaScript Scope.