Skip to content

Functions in JavaScript

Are you tired of writing the same code over and over again?
Do you wish there was a simpler way to write something once and reuse it anywhere with just a reference?

Well, guess what? You’re in luck! JavaScript has exactly what you need, and it’s called functions.

When we were kids, we learned how to count and add numbers, right? Maybe we even used our fingers at first.

But here’s something interesting; once we mastered that process, we didn’t have to relearn it every time someone asked us to add two numbers. Our brain simply recalled the stored logic and executed it automatically.

That’s exactly how functions work in JavaScript.

Once you’ve written a piece of logic like “how to add two numbers”, you don’t have to rewrite it again.
You define it once inside a function, and then you can call that function whenever you need it.

Just like how our brain reuses the logic from the memory, our code can also reuse certain parts as well.

Up next, let’s see how to actually define and call functions in JavaScript.

A function is a block of code, that can be reused multiple times across our codebase.

To define a function, we start with keyword function followed by a name & Parenthesis () and then a curly braces where we write our code.

function hello(){
    // here you will write some code...
    console.log("Hello Friend!")
}

In the above example we can observe that:

  1. We start with keyword function.
  2. The name of the function is hello and is followed by parentheses.
  3. Inside curly braces, we write a simple console log statement.
  4. Till now we just define the function.

To execute the function we simply write function name followed by Parenthesis().

function hello(){
    // here you will write some code...
    console.log("Hello Friend!")
}

hello(); // calls the function. Outputs "Hello Friend"

In the above example we called the function hello() and it prints Hello Friend! in console.

Now, You might be thinking “but why parentheses ()”?

Well If we see the above function is quite has a hardcoded text in it i.e. “Hello Friend”. We say in variables, that we can provide different value based on variables. What if we could make this text dynamic?

Parenthesis allows us to take Parameters which are nothing but variables as input. These variables are fist used inside function definition to define what we want to input and when we call the function we provide arguments (values) of those variables.

Let’s modify above example:

function hello(name){
    // here you will write some code...
    console.log(`Hello ${name}!`)
}

hello("Manmeet"); // calls the function. Outputs "Hello Manmeet!"

In the above example we can observe that:

  1. We have a parameter names name during function definition.
  2. We use String template literals to pass the name variable inside the String.
  3. We called the function with value for variable name as Arguments.
  4. Functions print Hello Manmeet in output.

There you go, now we have made our function dynamic.

Now you might be wondering:

Hmm Okay. But how does this solve my problem of preventing reusing code?

Good Question. Let’s take an example Shall we?

Suppose we need to send an email to multiple new employees with their information such as name, role, and employee ID:

console.log(`
    Welcome Aboard Rahul,

    We are excited to have you on our team. Here's your information:
    Name: Rahul Singh
    Role: Junior Support Engineer
    EmployeeID: ES241
`)
console.log(`
    Welcome Aboard Priya,

    We are excited to have you on our team. Here's your information:
    Name: Priya Koul
    Role: Associate HR
    EmployeeID: HR102
`)
console.log(`
    Welcome Aboard Priyansh,

    We are excited to have you on our team. Here's your information:
    Name: Priyansh Kumar
    Role: Junior Frontend Dev
    EmployeeID: DEV24
`)

In the above example, we can observe that:

  1. The structure of the message is identical for every employee.
  2. Only a few details (name, role, employeeID) change.
  3. We’re repeating the same code over and over again

Let’s make a reusable welcome template, with functions:


function welcomeEmployee(name, role, employeeID){
    console.log(`
    Welcome Aboard ${name.split(" ")[0]},

    We are excited to have you on our team. Here's your information:
    Name: ${name}
    Role: ${role}
    EmployeeID: ${employeeID}
`)
}

// call functions
welcomeEmployee("Rahul Singh", "Junior Support Engineer", "ES241")
welcomeEmployee("Priya Koul", "Associate HR", "HR102")
welcomeEmployee("Priyansh Kumar", "Junior Frontend Dev", "DEV24")

In the above example, we can observe that:

  1. We created a simple template using functions.
  2. We passed Parameters like name, role and employeeID.
  3. We just called the function welcomeEmployee three times and it worked similar to previous example.

See how we just saved so much space and effort by wrapping the repeatable code in a function?

Now imagine sending this to 1,000 employees and all you’d need is one function call. That’s the real power of functions.

Till now, we’ve only been printing something to the console from our functions.
While that’s a valid approach, it’s not always the recommended one, especially when you’re trying to solve real problems or reuse logic elsewhere in your code.

The console.log() statement just shows the output on the screen. But most of the time, our program needs to use that output, not just display it.

That’s where the return keyword comes in.

The return statement allows a function to send back a value to the place where it was called.

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

const result = add(10, 5);
console.log(result); // 15

In the above code example, where we returns a + b operation, observe we are not printing it inside the function.

So if you just call the function like this, it won’t display anything on the screen.

const result = add(10, 5);// outputs nothing

This is where most developers get confused:

“Why is it not printing anything on the screen?”.

Well, think of it this way; it’s like asking someone to calculate 10 + 4 in their mind but not tell you the answer yet. They’ve done the math, but they’re holding the result privately until you ask for it.

Now, to get the answer, you need to ask the person:

“hey what’s the output of the problem I asked?”.

Similarly, in case of JavaScript, we need to use console.log or refer that variable to use the data.

console.log(result); // outputs 15

The above code example will output the result of the operation 15 on the screen.

You might be thinking:

Do functions only return numeric outputs?

Good question and the answer is No. A function can return any type of data, but it can only return one single entity at a time.

That entity, however, could be:

  • a number
  • a string
  • a boolean
  • an array
  • an object
  • or even another function (yes, functions can return functions, but I will cover this in another article)

Let’s look at a few examples.

function greet(name) {
  return `Hello ${name}, Welcome back!`;
}

const message = greet("Manmeet");
console.log(message); // Outputs: Hello Manmeet, Welcome back!
function isAdult(age) {
  return age >= 18; 
}

console.log(isAdult(20)); // Outputs true
console.log(isAdult(15)); // Outputs false

In this case, the function checks a condition and returns a boolean (true or false).

function getEvenNumbers() {
  return [2, 4, 6, 8, 10];
}

const evens = getEvenNumbers();
console.log(evens); // Outputs: [2, 4, 6, 8, 10]

In this case, the function will return an Array, which is collection of same elements.

function createUser(name, role) {
  return {
    name: name,
    role: role
  };
}

const user = createUser("Rahul", "Frontend Developer");
console.log(user); // Outputs: { name: 'Rahul', role: 'Frontend Developer' }

In this case, the function will return an object is one of the most common patterns in real-world development,


Great! Till now, we’ve learned what functions are, how to call them, and even how to return values.
But did you know there’s more than one way to define a function in JavaScript?

Yes, you can create functions in multiple ways, each with its own purpose and behavior.

This is the most common and traditional way to define a function, the one we’ve been using so far.
We use the function keyword, followed by the function name, parentheses (), and curly braces {}.

function normalFunction() {
  console.log("Hey there! I'm a normal function.");
}

normalFunction(); // Outputs: Hey there! I'm a normal function.

Key Points:

  1. Functions defined this way are called Function Declarations.
  2. Great for reusable logic or when order doesn’t matter.

Normal Function in a Variables (Function Expression)

Section titled “Normal Function in a Variables (Function Expression)”

We can also assign a function to a variable. The function itself behaves the same, but how it’s defined and executed is slightly different.

const variableFunction = function (){
    console.log("Hello, I'm a Normal Function in Variable");
}
variableFunction(); // Outputs: Hello, I'm a Normal Function in Variable

Key Points:

  1. This is called a Function Expression.
  2. The function is assigned to a variable (in this case, variableFunction).

Now comes the modern JavaScript style of declaring functions known as Arrow Functions. They were introduced in ES6 (2015) as a shorter, cleaner syntax for writing functions.

const arrowFunction = () => {
  console.log("Hey, I'm an Arrow Function!");
};

arrowFunction(); // Outputs: Hey, I'm an Arrow Function!

if your arrow function just returns a single value, you can make it even shorter without need for curly braces {} or the return keyword.

const add = (a, b) => a + b;
console.log(add(5, 3)); // 8

To return something like Object using this Shorter Syntax, we use object wrapped inside of parentheses.

const returnUser = () => ({name: "Rahul", role: "Frontend Developer"})

This shorter syntax is called an implicit return.

Key Points:

  1. Uses the => syntax instead of the function keyword.
  2. Always assigned to a variable (like Function Expressions).
  3. Arrow Functions are great for short, simple functions like callbacks or one-liners.

IIFE (Immediately Invoked Function Expression)

Section titled “IIFE (Immediately Invoked Function Expression)”

So far, the functions we’ve worked with follow two steps: declaration and calling.
In the declaration phase, we define the function and the code it will execute.
In the calling phase, we manually invoke that function using its name.

But what if we need a function that runs immediately without having to call it manually?

That’s where IIFE comes into the picture.

IIFE stands for Immediately Invoked Function Expression.

It’s a function that is defined and executed instantly, right after its creation.

;(
  function test() {
    console.log("This is a TEST IIFE");
  }
)(); // Outputs: This is a TEST IIFE

;(() => {
  console.log("IIFE using Arrow Function");
})(); // Outputs: IIFE using Arrow Function

From above code example we observe that:

  1. IIFE is a function which immediately executes after it’s creation.
  2. It uses one pair of parentheses to wrap the function and another to execute it ()();
  3. In many codebases, IIFEs start with a semicolon ; to prevent issues if the previous line of code doesn’t end properly (especially when multiple scripts are concatenated).

We can also pass parameters inside of the IIFE like:

;((name) => {console.log(`Welcome ${name}`)})("Manmeet") // Outputs: Welcome Manmeet

In the above example:

  1. The first parentheses wrap the arrow function and define a parameter name.
  2. The second parentheses provide the argument (“Manmeet”).
  3. The function executes instantly, printing the message right away.

Functions are the heart of JavaScript. They help you organize logic, reuse code, and keep your programs clean and efficient.

You learned how to:

  • Define and call functions
  • Pass parameters and return values
  • Make functions reusable and dynamic
  • Write them in different styles such as normal, expression, IIFE and arrow

No matter how you define them, the goal is simple write once, reuse often.