DEV Community

Cover image for All About Functions in Javascript
INDRANIL MAITI
INDRANIL MAITI

Posted on

All About Functions in Javascript

Functions are one of the main fundamental building blocks of Javascript. These are necessary for building web applications. Before going into details, let us have some motivation.

Motivation

In our daily life, certain tasks are handled by specific people who specialize in them. For example, when you need a piece of furniture, you go to a carpenter. In the same way, in web applications, functions are created to handle specific tasks.

Let’s say in your application you need to access user data—like their username or subscription status—at multiple places. You have two choices: either you write the same logic every single time, or you write it once as a function and simply call that function wherever it's needed.

Clearly, the second option is a game-changer, right?
It not only saves you from repeating code but also gives your application a neat and modular structure.

Don’t worry if this feels a bit new—we’ll make it clearer as we go deeper into the topic!

Structure of a Function

As we have understood from the previous section function is a set of instructions that performs a task. There is also a superpower to function that it can take some inputs which it processes through the set of instructions you have given and gives us the output.
Let us have an example, you are looking to build a function that calculates the total price of the customer's cart before checkout. So you want a simple addition of prices (this is the task of the function). But to perform this task, you need to provide the amount as input of the function. These are called parameters.
Let us see an example,

function calculateTotal(prices) {
  let total = 0;
  for (let i = 0; i < prices.length; i++) {
    total += prices[i];
  }
  return total;
}
Enter fullscreen mode Exit fullscreen mode

A function definition consists of the function keyword followed by
- The name of the function. Here it is calculateTotal
- A list of parameters to the function, enclosed in parentheses and separated by commas. Here it is prices
- The JavaScript statements that define the function, enclosed in curly braces, { /* … */ }. Here it is let total = 0;
for (let i = 0; i < prices.length; i++) {
total += prices[i];
}
return total;

An important note: Generally there should be an return statement at the end of the function which will be the function's output. Also, a function can return another function as well!

How to Use the function

This is pretty simple. Just Call the function by its name along with the parameters.

const cart = [29.99, 15.50, 9.99];
const totalPrice = calculateTotal(cart)
console.log(totalPrice)
Enter fullscreen mode Exit fullscreen mode

Function Expression

The above way of representing the function is generally known as Function Declaration. There is another kind of representation of functions which is known as Function Expression. The representation in this case is

const calculateTotal = function (prices) {
  let total = 0;
  for (let i = 0; i < prices.length; i++) {
    total += prices[i];
  }
  return total;
}

Enter fullscreen mode Exit fullscreen mode

The main difference here is you can omit the name of the function.

Why Use Function Expressions

1. Callbacks & Event Handlers
Use Case: Responding to user actions like clicking a button.You can define the logic inline without needing a separate named function.

document.getElementById("subscribeBtn").addEventListener("click", function () {
  alert("Thank you for subscribing!");
});

Enter fullscreen mode Exit fullscreen mode

2. Defining Methods Inside Objects
Use Case: Creating an object with methods for business logic. Method is defined inline inside the object, making the structure clean and readable.

const cart = {
  items: [],
  addItem: function (item) {
    this.items.push(item);
    console.log(`${item} added to cart.`);
  },
};
cart.addItem("T-shirt"); // T-shirt added to cart.

Enter fullscreen mode Exit fullscreen mode

3. Conditional or Dynamic Logic
Use Case: Define different functions based on user role or environment. Assign function dynamically based on condition.

const user = { isAdmin: true };

const accessControl = user.isAdmin
  ? function () {
      console.log("Access granted to admin panel.");
    }
  : function () {
      console.log("Access denied.");
    };

accessControl(); // Output depends on user role

Enter fullscreen mode Exit fullscreen mode

Arrow Function

There is a compact alternative to Function Expressions in modern day web applications. This is known as Arrow Function. The most common syntax is

(params) => {
  statements
}
//Example
(a, b) => {
  return a + b + 100;
}
Enter fullscreen mode Exit fullscreen mode

If the body has statements, the braces are required — and so is the return keyword. The braces can only be omitted if the function directly returns an expression.

(a,b) => a+b+100
Enter fullscreen mode Exit fullscreen mode

Lexical Scope and Closure

There is one more important concept related to functions in Javascript i.e. Lexical Scope and Closure. Lexical scope is known as how the variables defined in the function can be accessed based on the placement of the variable. Let us see an example to understand this better

function outer() {
  const message = "Hello, ";

  function inner(name) {
    console.log(message + name);
  }

  return inner;
}

const greet = outer();
greet("Alice"); // Outputs: Hello, Alice
Enter fullscreen mode Exit fullscreen mode

Here, message variable is defined in the outer function and outer function also has another function defined as inner. Look outer function is returning the function inner.
Here, inner function has access to the variable message though it has been defined outside inner function. This is because javascript uses lexical scoping means it looks for variables where the function was defined. Here inner function is inside the scope of outer function. On the other hand outer function does not have any access to any variable defined in inner function because any variable defined inner function is not inside the scope of outer fucntion.

On the other hand, a closure is closely related to lexical scope. It occurs when a function “remembers” the variables from its outer lexical scope, even after that outer function has finished executing. This behavior allows functions to maintain access to their parent’s variables, even if they would normally go out of scope.
Let's see an example

function init() {
  var name = "Indra";
  function displayName() {
    console.log(name); 
  }
  displayName();
}
let res = init();
res() // output: Indra

Enter fullscreen mode Exit fullscreen mode

Look very carefully here, let res = init() in this line init function has been executed so you might think the variable name does not exist anymore and we might get an error while calling the function res() in the next line. Here comes the context of closure. In JS when you call the function init() in the res variable not only the displayName function comes but it comes along with the lexical scope of init function too.

I hope this helps you in understanding the concept of Function in Javascript.

Top comments (0)