BBlogspage

Everything You Need to Know About JavaScript Functions – Beginner to Pro

  • Mastering JavaScript Functions: From Basics to Advanced Concepts

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 function:

JavaScript

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:

JavaScript

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.

JavaScript

// 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.

JavaScript

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.

JavaScript

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.
  • Arguments are the actual values passed when invoking the function.

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.

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.

JavaScript

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

person(2000); // Output: Hey! You are 25 years old
person(); // Default value assigned. Output: Hey! You are 30 years old

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.

JavaScript

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

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

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

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.

JavaScript

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().

JavaScript

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:

  • Creates a private scope, preventing global scope pollution.
  • Executes immediately upon definition, making it useful for initializing code.

JavaScript

(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.

JavaScript

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

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

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

Arrow Function Writing Styles:

  • 0 parameters – Use empty () parentheses.
  • 1 parameter – Parentheses are optional (can write without ()).
  • More than 1 parameter – Must use () to wrap parameters.
  • Multi-line function – Code wrapped in {} and requires an explicit return.
  • Single-line function – No need to wrap code in {} (implicit return).

JavaScript

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

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

// Multiple parameters
const addParams = (a, b) => a + b;

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

Note on Disadvantages: Arrow functions don’t have their own this context. They inherit this from the surrounding lexical scope. Hence, arrow functions should usually be avoided inside objects as methods.

12. Function Hoisting in JavaScript Functions

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.

JavaScript

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

function addNumbers(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.

14. Higher-Order Function

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()

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

  • Callback Function: A function that is passed as an argument to another function and executed later.
  • Higher-Order Function: A function that takes another function as an argument or returns a function as its result.

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

JavaScript

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

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

15. Inner Function in Javascript Functions

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.

Key Points About Inner Functions:

  • Scope Access: An inner function can access variables from the outer function. Variables inside the inner function remain private, are not accessible globally, and encapsulate logic.
  • Closure Formation: If an inner function is returned from the outer function, it forms a closure.

JavaScript

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 forms a closure.

JavaScript

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

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

let outerInstance = outerReturn();
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.

JavaScript

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

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

let profileInstance = createProfile();
console.log(profileInstance.age); // Output: 24

18. Recursion in JavaScript Functions

Recursion in JavaScript occurs when 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.

JavaScript

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 JavaScript Functions Features)

19. Closures

A closure is a feature of JavaScript 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?

  • Data Privacy: Variables remain private and cannot be accessed directly from outside.
  • Maintaining State in Asynchronous Code: Useful in callbacks and event handlers.
  • 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.

20. Function Currying

Function Currying is a technique 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.

JavaScript

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

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

How the above code executes:

  • addCurry(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.
  • addCurry(5) returns a function that permanently remembers a = 5.

21. Generator Functions (ES6)

A generator function is a special type of function in JavaScript 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.

JavaScript

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 a 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:

  • 10 Tips to Write CSS Faster and More Efficiently for New Web Developers
  • Starting with SaaS in VSCode
  • Type conversion VS Type coercion in JavaScript
  • JavaScript Data Types in Web Technology for Beginners
  • How to Create an Image Gallery with Filter Buttons in Just 10 Minutes!
  • Create Website Slider with HTML, CSS & Swiper.js!