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.
Analogy
Section titled “Analogy”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.
What are functions?
Section titled “What are functions?”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:
- We start with keyword
function. - The name of the function is
helloand is followed by parentheses. - Inside curly braces, we write a simple console log statement.
- 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.
Why Parenthesis ()?
Section titled “Why Parenthesis ()?”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:
- We have a parameter names
nameduring function definition. - We use String template literals to pass the
namevariable inside the String. - We called the function with value for variable
nameas Arguments. - Functions print
Hello Manmeetin output.
There you go, now we have made our function dynamic.
How is it reusable?
Section titled “How is it reusable?”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:
- The structure of the message is identical for every employee.
- Only a few details (name, role, employeeID) change.
- 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:
- We created a simple template using functions.
- We passed Parameters like
name,roleandemployeeID. - We just called the function
welcomeEmployeethree 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.
Returning a Value
Section titled “Returning a Value”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.
What Does return Do?
Section titled “What Does return Do?”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.
Returning Different Data Types
Section titled “Returning Different Data Types”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.
1. Returning a String
Section titled “1. Returning a String”function greet(name) {
return `Hello ${name}, Welcome back!`;
}
const message = greet("Manmeet");
console.log(message); // Outputs: Hello Manmeet, Welcome back!
2. Returning a Boolean
Section titled “2. Returning a Boolean”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).
3. Returning an Array
Section titled “3. Returning an Array”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.
4. Returning an Object
Section titled “4. Returning an Object”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,
Different Ways to Define Functions
Section titled “Different Ways to Define Functions”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.
Normal Function (Function Declaration)
Section titled “Normal Function (Function Declaration)”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:
- Functions defined this way are called Function Declarations.
- 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:
- This is called a Function Expression.
- The function is assigned to a variable (in this case, variableFunction).
Arrow Functions (The Modern Way)
Section titled “Arrow Functions (The Modern Way)”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!
Shorter Syntax
Section titled “Shorter Syntax”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:
- Uses the => syntax instead of the function keyword.
- Always assigned to a variable (like Function Expressions).
- 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:
- IIFE is a function which immediately executes after it’s creation.
- It uses one pair of parentheses to wrap the function and another to execute it
()(); - 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:
- The first parentheses wrap the arrow function and define a parameter name.
- The second parentheses provide the argument (“Manmeet”).
- The function executes instantly, printing the message right away.
🧵 Wrapping It Up
Section titled “🧵 Wrapping It Up”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.