CS Engineering Gyan

JavaScript Functions

Functions are one of the most important concepts in JavaScript programming. A function is a reusable block of code designed to perform a specific task.

Instead of writing the same code multiple times, developers can create a function once and use it whenever required. Functions help make programs shorter, organized, and easier to maintain.

Almost every modern JavaScript application uses functions. Websites, web applications, games, APIs, and interactive features depend heavily on functions to organize programming logic.


What is a Function in JavaScript?

A function is a group of statements that performs a particular operation. It executes only when it is called or invoked.

Functions allow programmers to divide a large program into smaller reusable parts. This approach makes code easier to understand, debug, and update.

Example Without Function


let a = 10;
let b = 20;

console.log(a + b);


let x = 30;
let y = 40;

console.log(x + y);

The above code performs addition multiple times, but the same logic is repeated. Functions help remove this repetition.

Example Using Function


function add()
{

    let a = 10;

    let b = 20;

    console.log(a + b);

}


add();

Output


30


Why are Functions Important?

Functions improve the quality of JavaScript programs by providing code reusability and better organization.

Advantages of Functions


Types of Functions in JavaScript

JavaScript supports different types of functions according to programming requirements.

Function Type Description
Function Declaration A normal function created using the function keyword.
Function Expression A function stored inside a variable.
Arrow Function A shorter syntax introduced in ES6.
Anonymous Function A function without a name.
Callback Function A function passed as an argument to another function.

Function Declaration in JavaScript

A function declaration is the most common way to create a function in JavaScript. It uses the function keyword followed by the function name.

Syntax


function functionName()
{

    // Statements

}


Example: Creating a Simple Function


function message()
{

    document.write("Welcome to JavaScript");

}


message();

Output


Welcome to JavaScript

In this example, the function named message() is created first and executed by calling its name.


Calling a Function

Creating a function does not execute its code automatically. A function must be called to run the statements written inside it.

Example


function display()
{

    console.log("JavaScript Function");

}


display();

display();

Output


JavaScript Function

JavaScript Function

A function can be called multiple times, which is one of its biggest advantages.


Function Parameters

Parameters are variables used inside a function to receive values from outside the function.

They allow functions to work with different data values without changing the function code.

Syntax


function functionName(parameter1, parameter2)
{

    // Statements

}


Example: Function with Parameters


function add(a, b)
{

    let sum = a + b;

    document.write(sum);

}


add(10,20);

Output


30

Here, a and b are parameters, while 10 and 20 are arguments passed during the function call.


Parameters vs Arguments

Parameters Arguments
Variables defined in function declaration. Actual values passed while calling a function.
Receive input values. Provide values to the function.
Example: function add(a,b) Example: add(10,20)

Multiple Parameters Example


function student(name, age)
{

    document.write(name);

    document.write(age);

}


student("Rahul",21);

Output


Rahul

21



Return Value in JavaScript Functions

A function can return a value back to the place where it was called. The return statement is used to send a result from a function to the main program.

When a function returns a value, that value can be stored in a variable or used directly in another operation.

Syntax


function functionName()
{

    return value;

}


Example: Function with Return Value


function add(a, b)
{

    return a + b;

}


let result = add(20,30);


document.write(result);

Output


50

In this example, the function calculates the addition and returns the result. The returned value is stored inside the result variable.


Example: Calculate Square of a Number


function square(number)
{

    return number * number;

}


let answer = square(5);


document.write(answer);

Output


25


Rules of return Statement


Function Without Return Value

A function does not always need to return a value. Some functions only perform an action such as displaying a message or updating webpage content.

Example


function welcome()
{

    document.write("Welcome Student");

}


welcome();

Output


Welcome Student


Default Parameters in JavaScript

Default parameters allow developers to assign a default value to a function parameter. If no value is provided during the function call, JavaScript uses the default value.

Syntax


function functionName(parameter = defaultValue)
{

    // Statements

}


Example: Default Parameter


function greet(name = "User")
{

    document.write("Hello " + name);

}


greet();

Output


Hello User

Since no argument is passed, the function uses the default value "User".


Example: Using Custom Value


function greet(name = "User")
{

    document.write("Hello " + name);

}


greet("Rahul");

Output


Hello Rahul


Function Expression in JavaScript

A function expression is a function stored inside a variable. Unlike function declarations, function expressions are created during program execution.

Syntax


let variableName = function()
{

    // Statements

};


Example: Function Expression


let message = function()
{

    document.write("Learning JavaScript Functions");

};


message();

Output


Learning JavaScript Functions


Anonymous Function

An anonymous function is a function that does not have a name. These functions are commonly used as values assigned to variables or passed as arguments to other functions.

Example


let display = function()
{

    console.log("Anonymous Function");

};


display();

Output


Anonymous Function


Difference Between Function Declaration and Function Expression

Function Declaration Function Expression
Created using function keyword with a name. Stored inside a variable.
Can be called before declaration. Usually called after creation.
Loaded during JavaScript execution phase. Created when execution reaches the statement.
Easy to use for normal functions. Useful for dynamic programming.

Arrow Functions in JavaScript

Arrow functions were introduced in ECMAScript 6 (ES6). They provide a shorter syntax for writing functions and are widely used in modern JavaScript development.

Arrow functions are especially popular when working with arrays, callbacks, and modern JavaScript frameworks.

Syntax


let functionName = () =>
{

    // Statements

};


Example: Simple Arrow Function


let message = () =>
{

    document.write("Hello JavaScript");

};


message();

Output


Hello JavaScript


Arrow Function with Parameters


let add = (a,b) =>
{

    return a + b;

};


document.write(add(10,20));

Output


30


Short Arrow Function Syntax

If an arrow function contains only one statement, curly braces and the return keyword can be removed.

Example


let multiply = (a,b) => a*b;


document.write(multiply(5,4));

Output


20


Difference Between Normal Function and Arrow Function

Normal Function Arrow Function
Uses function keyword. Uses arrow symbol (=>).
Has its own this value. Uses this from surrounding scope.
Longer syntax. Short and compact syntax.
Used in traditional JavaScript. Commonly used in modern JavaScript.

Function Scope in JavaScript

Scope determines where a variable can be accessed inside a program. JavaScript functions create their own scope.

Variables declared inside a function are accessible only within that function. Variables declared outside functions can usually be accessed from inside functions.


Local Variable

A variable declared inside a function is called a local variable. It can only be used inside that function.

Example


function display()
{

    let message = "Hello";

    document.write(message);

}


display();

The variable message exists only inside the display function.


Global Variable

A variable declared outside all functions is called a global variable. It can be accessed from different parts of the program.

Example


let name = "JavaScript";


function show()
{

    document.write(name);

}


show();

Output


JavaScript



Callback Functions in JavaScript

A callback function is a function that is passed as an argument to another function and executed later. Callback functions are an important concept in modern JavaScript because they allow developers to control the execution order of tasks.

Callbacks are commonly used with events, timers, API requests, and asynchronous programming.

Syntax


function mainFunction(callback)
{

    callback();

}


Example: Simple Callback Function


function displayMessage()
{

    document.write("Welcome to JavaScript");

}


function execute(callback)
{

    callback();

}


execute(displayMessage);

Output


Welcome to JavaScript

In this example, the displayMessage function is passed to another function and executed inside it.


Example: Callback with Parameters


function calculate(a,b,operation)
{

    return operation(a,b);

}


function add(x,y)
{

    return x+y;

}


let result = calculate(10,20,add);


document.write(result);

Output


30


Higher Order Functions in JavaScript

A higher order function is a function that accepts another function as an argument or returns a function as its result.

JavaScript treats functions as first-class objects, which means functions can be stored in variables, passed as arguments, and returned from other functions.

Example


function message()
{

    return function()
    {

        document.write("Hello JavaScript");

    }

}


let result = message();


result();

Output


Hello JavaScript


Common JavaScript Higher Order Functions

JavaScript provides several built-in higher order functions that make working with arrays easier.

Function Description
map() Creates a new array by modifying each element.
filter() Creates a new array containing matching elements.
reduce() Combines all array values into a single result.
forEach() Executes a function for every array element.

Recursive Functions in JavaScript

A recursive function is a function that calls itself repeatedly until a specific condition is satisfied.

Recursion is useful for solving problems that can be divided into smaller similar problems, such as factorial calculation, searching, and tree-based operations.

Syntax


function functionName()
{

    functionName();

}


Example: Factorial Using Recursion


function factorial(number)
{

    if(number == 1)
    {

        return 1;

    }

    else
    {

        return number * factorial(number - 1);

    }

}


document.write(factorial(5));

Output


120

The function continues calling itself until the base condition is reached.


Important Parts of Recursive Functions


Immediately Invoked Function Expression (IIFE)

An Immediately Invoked Function Expression (IIFE) is a function that executes automatically immediately after it is created.

IIFE functions are useful for creating private variables and avoiding global namespace pollution.

Syntax


(function()
{

    // Statements

})();


Example: IIFE Function


(function()
{

    document.write("Function executed automatically");

})();

Output


Function executed automatically


Rest Parameters in JavaScript Functions

Rest parameters allow a function to accept an unlimited number of arguments. They are represented using three dots (...).

Syntax


function functionName(...parameters)
{

    // Statements

}


Example: Using Rest Parameter


function add(...numbers)
{

    let sum = 0;


    for(let number of numbers)
    {

        sum = sum + number;

    }


    return sum;

}


document.write(add(10,20,30,40));

Output


100


Spread Operator with Functions

The spread operator uses three dots (...) to expand array elements into individual values.

It is commonly used when passing array data as function arguments.

Example


let numbers = [10,20,30];


function add(a,b,c)
{

    return a+b+c;

}


document.write(add(...numbers));

Output


60


Real-World Applications of JavaScript Functions

Functions are used everywhere in modern web development. They help organize application logic and perform specific tasks.


Common Mistakes While Using Functions


Best Practices for JavaScript Functions


JavaScript Functions Interview Questions

  1. What is a function in JavaScript?
  2. Why are functions used in programming?
  3. What is the difference between parameters and arguments?
  4. Explain function declaration and function expression.
  5. What is a return statement?
  6. What are default parameters?
  7. What are arrow functions?
  8. What is the difference between normal functions and arrow functions?
  9. What is a callback function?
  10. Explain higher order functions.
  11. What is recursion in JavaScript?
  12. What is an IIFE function?
  13. What are rest parameters?
  14. What is the spread operator?
  15. Explain local and global variables.

Summary

JavaScript functions are reusable blocks of code that help developers create organized and efficient programs. Functions reduce code repetition and make applications easier to develop, test, and maintain.

JavaScript supports different types of functions including function declarations, function expressions, arrow functions, callback functions, and recursive functions. Advanced concepts like higher order functions, IIFE, rest parameters, and spread operators make JavaScript more powerful.

A strong understanding of functions is essential for learning advanced JavaScript topics such as objects, arrays, DOM manipulation, events, promises, and asynchronous programming.


← Previous: JavaScript Loops Next: JavaScript Arrays →
Home Visit Our YouTube Channel