Everything You Need to Know About JavaScript Functions โ€“ Beginner to Pro

ravindra kambleravindra kamble
11 min read

I believe that JavaScript functions are one of the most valuable concepts to master when learning JavaScript. JavaScript functions play a critical role in coding by providing reusability, encapsulation, and a robust code structure. With ES6, several new advancements have been introduced in JavaScript functions, making them even more powerful.

In this article, I will guide you through mastering JavaScript functions, starting from the basics and progressing to the most advanced concepts.

Basic Concepts (Fundamentals of JavaScript Functions)

1. What is a Function?

A function is a reusable block of code designed to perform a specific task. JavaScript functions are written to reuse programming logic, maintain clean and readable code, encapsulate logic, and manage scope effectively.

Like JavaScript, functions exist in almost every programming language. Below is an example of a JavaScript functions:

function welcome()
{
 console.log("Welcome to the Blogspage!);
}

welcome(); //output: Welcome to the Blogspage!

2. JavaScript functions declaration and Invocation

In JavaScript, functions must be declared first before they can be called whenever needed. Calling a function is also known as function invocation. A function can be called multiple times, passing different arguments each time to achieve dynamic results.

The example below demonstrates how JavaScript functions work:

function addition(a,b)  // function declared
{
   console.log(a+b);
}

addition(5,2); // function called , Output: 7
addition(10,10); // function called,  Output: 20

3. Named Functions

A named function is one of the most basic types of JavaScript functions. It is defined using the function keyword, followed by a unique function name. One of the key advantages of named functions is that they support hoisting, meaning they can be called before their actual declaration in the code.

//Example of Named Function
function greet()
{
   console.log("Welcome 2025!);
}

greet();

4. Function Expression

In a function expression, a function is defined and assigned to a variable. Unlike named functions, function expressions do not support hoisting, meaning they cannot be called before their declaration.

Function expressions are commonly used in callbacks and higher-order functions to enhance flexibility and code reusability.

const myFun = function()
{
   console.log("Hello I am Function Expression");
}

myFun();

5. Function Inside an Object

A function can be defined inside an object, and when it is, it is called a method. It is recommended to avoid using arrow functions inside objects, as they do not bind their own this value, which can lead to unexpected behavior. Methods can be called directly using the object name, followed by the method name.

const myObj = {
  firstName :"Rahul",
      salary: function(sal){
             console.log(`One year salary is ${sal*12}`);
            }
   }

myObj.salary(1000); //output:12000

6. Javascript Functions Parameters and Arguments

In JavaScript functions, parameters and arguments play a crucial role in passing values to a function.

Parameters act as placeholders defined when the function is declared. In below example age, name are the parameters.

Arguments are the actual values passed when invoking the function. Below mentioned example value passed 32, "sunny" are the arguments.

A function can have zero or multiple parameters/arguments. To ensure proper execution, the sequence and count of arguments must match the sequence and number of parameters when calling the function.

javascript functions parameters and arguments

7. Default Parameters (ES6)

Default parameters were introduced in ES6 to ensure safe function execution when no arguments are passed. If a function is called without providing values, the parameters default to undefined.

By assigning default values to parameters, we can prevent unexpected behavior and ensure smooth execution. This is especially useful in situations where a function is invoked without arguments but still expects parameters.

function person(doy=1995)
{
  let currentAge = 2025-doy;
  console.log(`Hey! You are ${currentAge} years old`);
}

person(2000); // Output: Age 25 years
person(); //default value assigned to this function call Output: Age 30 years

8. The arguments Object

In JavaScript functions, there is a special type of object called the arguments object. It behaves like an array, allowing access to function arguments using indexing (e.g., arguments[2]) and the length property. However, unlike real arrays, the arguments object does not support all array methods.

To convert the arguments object into an actual array, you can use two methods:

Spread operator (...) โ€“ By using the spread syntax, you can assign the arguments object to a new array.

Array.from() โ€“ This method allows you to easily transform the arguments object into an array.

function newAdd(){
  console.log(arguments);
}

newAdd("Rock",59,"Teacher");

Output:
[Arguments] {
'0' : 'Rock',
'1' : 59,
'2' : 'Teacher'
}

Below mentioned example shows how to convert arguments object to array.

function newAdd(){

let person1 = Array.from(arguments); // Converted using Array.from() method

let person2 = [...arguments];  // Converted using spread operator
}

9. Rest Parameters (ES6)

The rest parameter (...) in JavaScript functions allows a function to accept an indefinite number of arguments as an array. This makes it easier to handle multiple parameters dynamically without needing to know the exact number of arguments in advance.

One important rule is that the rest parameter must always be the last parameter in a function definition. Rest parameters are a real array, so we can use array methods like map(), reduce(), and filter().

function newAdd(...info)
{
 console.log(info);
}
newAdd("Rock",59,"Teacher");

Output: ['Rock', 59, 'Teacher']

Intermediate Concepts (More Advanced Function Behavior)

10. IIFE (Immediately Invoked Function Expression)

An IIFE (Immediately Invoked Function Expression) is a JavaScript function that executes immediately after being defined. It is wrapped in parentheses, e.g., (function() { ... })();, and is invoked immediately using ().

Key Features of IIFE:

  1. Creates a private scope, preventing global scope of the function.

  2. Executes immediately upon definition, making it useful for initializing code.

Yuo can see in below example function invoked by placing () at the end of function.

(function()
{
  console.log("Hey! I am IIFE.");
})();

Output: 'Hey! I am IIFE.'

11. Arrow Function (ES6)

An arrow function (=>) is a concise way to write JavaScript functions, introduced in ES6. It simplifies function expressions by removing the need for the function keyword, making the code cleaner and more readable.

Arrow function make code shorter with compare to trandition function. Not required {} and function keyword in Arrow function.

// Traditional function
function add(a, b) {
    return a + b;
}

// Arrow function
const add = (a, b) => a + b;

console.log(add(5, 3)); // Output: 8

Below mentioned Arrow function writting styles.

๐Ÿ‘‰ 0 parameter - Use empty () parentheses

๐Ÿ‘‰ 1 parameter - Parentheses (()) are optional, can write without parentheses.

๐Ÿ‘‰ More than 1 parameters - Must use () to wrap parameters.

๐Ÿ‘‰ Mult-line function - Code wrapped in {}

๐Ÿ‘‰ Single line function - No need to wrap code in {}

// without parameter
const greet = () => "Hello! Welcome to Blogspage!";

//single parameter
const square = a => a*a;

//multiple parameters
const add = (a, b) => a + b;

// multiline function
const sub = (a,b) =>{
   let result = a-b;
   console.log(result);
}

Disadvantages of Arrow function - Arrow function don't have own this context. It will inherit this from surrounding scope. Hence arrow function will be avoided using inside object.

12. Function Hoisting

Function hoisting in JavaScript functions allows a function to be invoked before it is defined. However, only named functions support hoisting, while arrow functions and function expressions do not.

Hoisting is particularly useful in recursive functions, where a function needs to call itself before its definition appears in the code.

add(3,3);
console.log("Written before function")

function add(a,b)
{
  console.log(a+b);
}

Output: 
6
Written before function

13. Callback Function

In JavaScript functions, a callback function is a function passed as an argument to another function and executed later.

Callback functions are commonly used to handle asynchronous operations, maintain the order of execution, and promote code reusability.

callback function in javascript functions

In above code function add provided as arguments to function operations its called callback function.

14. Higher-Order Function

In JavaScript functions, a higher-order function is a function that either takes another function as an argument or returns a function as its result. JavaScript treats functions as first-class citizens, meaning functions can be assigned to variables, passed as arguments, and returned from other functions.

Built-in Higher-Order Functions in JavaScript:

  • map()

  • filter()

  • reduce()

  • forEach()

  • sort()

Higher-order functions play a crucial role in functional programming, improving code readability and reusability.

What is difference between higher-order function and callback function?

๐Ÿ‘‰ Callback Function: A function that is passed as an argument to another function and executed later. In above example add is callback function.

๐Ÿ‘‰ Higher-Order Function: A function that takes another function as an argument or returns a function as its result. In above example operations is higher-order function.

Below is an example of a higher-order function in JavaScript, where a function returns another function:

function multiplier(factor) {
    return function (number) {
        return number * factor;
    };
}

const double = multiplier(2);
console.log(double(5)); // Output: 10

15. Inner Function

An inner function is a function defined inside another function. It has access to the outer functionโ€™s variables and parameters due to lexical scoping in JavaScript functions.

Key Points About Inner Functions:

  • Scope Access - Inner function can access variables from the outer function and variables inside the inner function remain private and are not accessible globally and encapsulated logic.

  • Closure Formation - If an inner function is returned from the outer function, it forms a closure.

function outer()
{
  let firstName='Rocky';

  function inner()
  {
    let age = 24;
    console.log(`Hello ${firstName} you are ${age} years old.`)
  }
  inner();
}

outer();

16. Function Returning Another Function

In JavaScript functions, an inner function can be returned from an outer function. However, in this scenario, you cannot directly call the inner function. Instead, you need to:

  1. Create a reference to the outer function.

  2. This reference will hold the inner function as its return value.

  3. Calling this outer function reference will then execute the inner function.

This mechanism where function returns another function forms a closure.

function outer()
{
  let firstName='Rocky';

  return function inner()
  {
    let age = 24;
    console.log(`Hello ${firstName} you are ${age} years old.`)
  }
}

let outerInstance = outer();
outerInstance(); //inner function executed.

Output: Hello Rocky you are 24 years old.

17. Function Returning an Object

A function in JavaScript can return an object instead of a primitive value. This is useful when you want to return multiple related values or methods inside an object.

function outer()
{
  let firstName='Rocky';

  return {
     age:24,
     education: "High School",
     location:"South West Town"
  }
}

let outerInstance = outer();
console.log(outerInstance.age);

In above example instance of the function has been created, that instace used to call the object properties and methods.

javascript functions returns object

18. Recursion in JavaScript

Recursion in javascript where a function calls itself until a certain condition is met. It is commonly used for problems like factorial calculation, Fibonacci series, and tree traversal.

Every recursive function must have a base case (stopping condition) to prevent infinite loops.

function countDown(num) {
    if (num <= 0) { // Base Case
        console.log("Done!");
        return;
    }
    console.log(num);
    countDown(num - 1); // Recursive Call
}

countDown(5);

Advanced Concepts (More Complex Function Features)

19. Closures

A closure is a feature of JavaScript functions where an inner function remembers the variables from its outer functionโ€™s scope, even after the outer function has finished executing.

Why Are Closures Useful?

Closures provide several advantages, including:

  1. Data Privacy โ€“ Variables remain private and cannot be accessed directly from outside.

  2. Maintaining State in Asynchronous Code โ€“ Useful in callbacks and event handlers.

  3. Function Factories โ€“ Helps create multiple functions with their own independent scope.

Since the inner function still holds a reference to the outer functionโ€™s variables, closures prevent garbage collection of those variables as long as the inner function is accessible.

closures in javascript function

In the above example, the inner function mainCals() accesses and stores the variable from the outer function factorial(). Even after the outer function executes and returns, the stored value remains accessible within the inner function, forming a closure in JavaScript functions.

javascript functions advanced

20. Function Currying

Function Currying is a technique in JavaScript functions where a function is transformed into a sequence of smaller functions, each taking a single argument instead of multiple arguments at once.

This approach enhances reusability and allows for more customizable function execution.

function add(a) {
    return function (b) {
        return a + b;
    };
}

const addFive = add(5); // Stores a partially applied function
console.log(addFive(3)); // Output: 8
console.log(addFive(10)); // Output: 15

How above code executed:
๐Ÿ‘‰ add(a) is a higher-order function that returns another function.
๐Ÿ‘‰ The inner function takes b as an argument and remembers a using closures.
๐Ÿ‘‰ When the inner function is called with b, it returns a + b.
๐Ÿ‘‰ add(5) returns a function that remembers a = 5.

21. Generator Functions (ES6)

A generator function is a special type of function in JavaScript functions that allows you to pause and resume execution using the yield keyword.

Syntax of a Generator Function

A generator function is defined using the function* syntax:

function* generatorExample() {
    yield "First yield";
    yield "Second yield";
}

const gen = generatorExample();
console.log(gen.next()); // { value: "First yield", done: false }
console.log(gen.next()); // { value: "Second yield", done: false }
console.log(gen.next()); // { value: undefined, done: true }

Features of generator function

๐Ÿ‘‰ Use of function*: The asterisk (*) defines a generator function.
๐Ÿ‘‰ yield Statement: Pauses execution and returns a value.
๐Ÿ‘‰ next() Method: Resumes execution from the last yield.
๐Ÿ‘‰ Returns an Iterator: Each call to next() returns { value, done }.

I have carefully structured this article to maintain a logical flow, covering JavaScript functions from basic to advanced concepts. Mastering all the topics mentioned here will help you gain a strong command of JavaScript functions, enabling you to write efficient, reusable, and optimized code.

๐Ÿš€ Follow me on Twitter for more tips and updates : @ravindra5k

๐Ÿ’ก Check out my other articles:

4
Subscribe to my newsletter

Read articles from ravindra kamble directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

ravindra kamble
ravindra kamble