Login

Sign Up

Mastering Functions in JavaScript
Priyanshu Sharma

Posted on Aug 19, 2025 | Frontend

Mastering Functions in JavaScript

Have you ever used a calculator? You press 2 + 3, and it gives you 5.
Now imagine, instead of typing that again and again, you could teach the computer once how to add numbers, and then simply ask it whenever you want.

That’s exactly what a function does in programming.
πŸ‘‰ A function is like a small machine inside your program: you give it input, it does some work, and gives you an output.


πŸ”Ή What is a Function?

Think about real life:

  • A vending machine takes money + your choice (input), prepares the snack (process), and gives you chips (output).

  • A calculator takes numbers (input), adds them (process), and shows you the result (output).

πŸ‘‰ A function in JavaScript works the same way.
It is a reusable block of code designed to perform a specific task.

Why do we need functions?

  1. Reusability – Write once, use many times.
  2. Organization – Keeps code clean and structured.
  3. Avoids repetition – Saves time by not writing the same code again and again.

πŸ”Ή Function Definition (Declaring a Function)

To create a function in JavaScript, we use the function keyword.

function functionName(parameters) {
  // Code to execute
  return result; // optional
}

Example:

function greet() {
  console.log("Hello, welcome to JavaScript!");
}

πŸ‘‰ Here:

  • function β†’ keyword used to define a function.
  • greet β†’ name of the function.
  • () β†’ where we put parameters (inputs).
  • {} β†’ contains the block of code that runs when the function is called.

πŸ”Ή Calling (Using) a Function

Just defining a function does nothing. To use it, we must call (invoke) it by writing its name followed by ().

function greet() {
  console.log("Hello, welcome to JavaScript!");
}

This will not generate any output.
But after adding the calling syntax...

function greet() {
  console.log("Hello, welcome to JavaScript!");
}
greet(); // Output: Hello, welcome to JavaScript!

πŸ”Ή Parameters and Arguments

This is one of the most important concepts for beginners.

  • Parameters: Variables that act like placeholders inside a function.
  • Arguments: The actual values you pass when calling the function.

Example:

function greetUser(name) { // 'name' is a parameter
  console.log("Hello, " + name + "!");
}

greetUser("Priya");  // "Priya" is an argument
greetUser("Amit");   // "Amit" is an argument

πŸ‘‰ Think of parameters as empty boxes waiting to be filled. When we call the function, we fill those boxes with arguments.

We can pass more than one parameter:

function add(a, b) {
  console.log("The sum is:", a + b);
}

add(5, 10);  // Output: The sum is: 15
add(20, 30); // Output: The sum is: 50

πŸ”Ή The return Statement

Sometimes we don’t just want to print something; we want the function to give back a result that we can use later. This is where return comes in.

function square(num) {
  return num * num;
}

let result = square(4);
console.log(result); // 16

πŸ‘‰ Difference:

  • If we console.log inside the function, it only displays the result at the time of calling.
  • If we return the result, we can store it, use it at the time of calling or can use it later.

πŸ”Ή Types of Functions

1. Function Declaration (Traditional Way)

function sayHello() {
  console.log("Hello World!");
}

sayHello(); // Hello World!

πŸ‘‰ Important: Function declarations are hoisted, which means you can call them even before they are written in the code.

sayHi(); // Works!
function sayHi() {
  console.log("Hi there!");
}

2. Function Expression

Here, we store a function inside a variable:

const sayHello = function() {
  console.log("Hello World!");
};

sayHello();

πŸ‘‰ Key difference: Function expressions are not hoisted. You cannot call them before defining.

3. Arrow Functions (Modern Way)

Introduced in ES6 (2015), arrow functions are shorter and cleaner.

const sayHello = () => {
  console.log("Hello World!");
};
sayHello();

πŸ‘‰ If the function has only one line, we can write it even shorter:

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

πŸ‘‰ If returning an object, wrap it in parentheses:

const getUser = () => ({ name: "Priya", age: 22 });
console.log(getUser()); // { name: "Priya", age: 22 }

πŸ”Ή Default Parameters

We can give parameters default values in case no arguments are passed:

function greet(name = "Guest") {
  console.log("Hello, " + name);
}

greet("Priyanshu"); // Hello, Priyanshu
greet();            // Hello, Guest

Explanation:

  • If the user passes a value, that value is used.
  • If not, the default value "Guest" is used.
    This prevents errors when arguments are missing.

πŸ”Ή Rest Parameters (...)

Sometimes we don’t know how many arguments will be passed. The rest parameter collects them into an array.

function sum(...numbers) {
  let total = 0;
  for (let num of numbers) {
    total += num;
  }
  return total;
}

console.log(sum(1, 2, 3, 4)); // 10
console.log(sum(5, 10, 15));  // 30

Explanation:

  • ...numbers collects all arguments into an array.
  • We can then loop through them to calculate the sum.
    This is useful when we don’t know the exact number of inputs.

πŸ”Ή The arguments Object

Inside normal functions, JavaScript provides an arguments object that holds all arguments passed to the function.

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

showArgs(1, 2, 3, "hello");
// [1, 2, 3, "hello"]

⚠️ Note: Arrow functions do not have arguments. Use rest (...) instead.


πŸ”Ή Higher-Order Functions

A higher-order function is a function that:

  • Takes another function as input, OR
  • Returns a function as output.
function calculate(a, b, operation) {
  return operation(a, b);
}

function add(x, y) {
  return x + y;
}

function multiply(x, y) {
  return x * y;
}

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

πŸ‘‰ Here, calculate is a higher-order function because it takes another function (add or multiply) as input.


πŸ“ Final Example (Calculator Function)

function calculator(a, b, operation = "add") {
  if (operation === "add") return a + b;
  if (operation === "subtract") return a - b;
  if (operation === "multiply") return a * b;
  if (operation === "divide") return a / b;
}

console.log(calculator(10, 5));              // 15 (default add)
console.log(calculator(10, 5, "subtract")); // 5
console.log(calculator(10, 5, "multiply")); // 50
console.log(calculator(10, 5, "divide"));   // 2

πŸ’‘ With this knowledge, you now understand everything about functions in JavaScript β€” from the basics to slightly advanced concepts. Functions are the heart of programming, and mastering them will make the rest of JavaScript much easier.

Happy Coding!!

4 Reactions

0 Bookmarks

Read next

Priyanshu Sharma

Priyanshu Sharma

Dec 14, 24

3 min read

|

How to Setup & Install VS Code: A Beginner’s Guide

Priyanshu Sharma

Priyanshu Sharma

Dec 17, 24

6 min read

|

Essential VS Code Extensions for Developers