Skip to main content

Command Palette

Search for a command to run...

Mastering Functions In js

Updated
6 min read
Mastering Functions In js

In this blog we are gonna learn about functions in js and after reading this blog you will be master of functions.

Imagine you own a grocery shop. Every day you need to calculate the total price of items and then apply GST to the bill. If you do this calculation manually for every customer, it will take a lot of time and effort.

So instead of calculating it yourself again and again, you hire a person and explain the task to them once:
"Whenever I give you the price, calculate the total and apply GST."

Now every time you need the calculation, you simply call that person and give them the price, and they return the final amount.

Functions in JavaScript work in a very similar way.
Instead of writing the same code repeatedly, we define a function once and call it whenever we need that task to be performed.

Functions in js:

Function is just a reusable block of code which is executed when we call it the function can e return some value after performing some task or either perform some task.

How to create a function:

We use the function keyword to declare a function.

syntax:

function function_name(){
 //function body
 // write repeated code here
}

call a function:

function_name()

the function is executed when we call the function.

Passing parameter to a function:

let understand the parameters by creating a function which adds two numbers.

function add(a,b){
//here a and b are parameters
const result=a+b
return result
}

const ans=add(5,6) // function call
console.log(ans)

//Output
11

lets create a function for calculating the total Amount of the grocery list.

function calculateTotalAmount(groceryList) {
    let totalAmount = 0;

    for (let item in groceryList) {
        totalAmount += groceryList[item];
    }

    return totalAmount;
}

const groceries = {
    rice: 120,
    milk: 50,
    bread: 40,
    oil: 200
};

console.log(calculateTotalAmount(groceries));

//Output

410

Know every time you need to calculateTotalAmount you can call the function.

so when every you saw a task which you have to perform multiple times just make a function.

there are several types of functions:

  • function declaration

  • function expression

  • arrow function

function declaration:

the function above we made is a function declaration.

function applyGst(amount){
const gst=amount*0.18
return gst+amount
}
console.log(applyGst(100))
//Output
118

function expression:

function expression is another way to make a function, we assign a whole function to a variable.

let make a function expression which apply 10% discount on title bill and return that discount.

const calculateDiscount=function (bill){
   return bill*0.10
}

console.log(calculateDiscount(1000))

Output:

100

we will study about arrow functions in the next blog.

Difference between function declaration and function expression:

Feature Function Declaration Function Expression
Definition Function is defined with the function keyword and a name. Function is assigned to a variable.
Syntax function greet(){} const greet = function(){}
Hoisting Fully hoisted — can be called before it is defined. Not fully hoisted — cannot be used before assignment.
Function Name Must have a name. Can be anonymous or named.
Usage Often used for reusable functions in the whole program. Often used for callbacks or assigning functions to variables.

Hoisting:

Hoisting in JavaScript means that variable and function declarations are moved to the top of their scope during the compilation phase, before the code is executed.

Let's understand the impact of hoisting and why it occurs.

When JavaScript code runs, a Global Execution Context is created. Inside this execution context, the code runs in two phases:

  • Memory Phase

  • Execution Phase


Memory Phase

Before executing the code, JavaScript scans the entire file and allocates memory for variables and functions. During this phase, some initial assignments also occur.

  • Function declarations are stored in memory along with their complete function body.

  • Variables declared with var are allocated memory and initialized with undefined.

  • Variables declared with let and const are allocated memory but are not initialized immediately. They remain in a state called the Temporal Dead Zone (TDZ) until their declaration is reached in the code.


Execution Phase

In the execution phase, JavaScript executes the code line by line.

Since memory for variables and functions has already been prepared in the memory phase, JavaScript can access them during execution. This behavior is what leads to hoisting.

The memory phase always runs before the execution phase.

Now lets take some example and understand the impact of hoisting.

console.log(x)
var x=10;

//Output
undefined
  • x was allocated in the memory phase

  • It was initialized with undefined

  • During execution, console.log(x) runs before x = 10

greet()
function greet(){
console.log("Namaste")
}


//Output 
Namaste

we can call a function before its creation when it created with declaration syntax because function declaration get fully hoisted.

greet()
const greet=function(){
console.log("Namaste")
}

Here, a ReferenceError occurs because variables declared with let and const are not accessible before they are initialized.

Although let and const are hoisted during the memory phase, they remain in a state called the Temporal Dead Zone (TDZ) until the execution reaches their declaration.

When to Use Each Type of Function

JavaScript provides different ways to create functions, such as function declarations, function expressions, and arrow functions. Each of them is useful in different situations.

1. Function Declaration

Function declarations are best used when the function is a core part of your program and may be used in multiple places.

Since function declarations are fully hoisted, they can be called before their definition in the code.

function calculateTotal(price, tax){
  return price + tax;
}

Use function declarations when:

  • The function is reusable in many places

  • You want clear and readable code

  • The function represents a main feature of the program

Function Expression

Function expressions are useful when a function needs to be assigned to a variable or passed around as a value.

Example:

const calculateDiscount = function(bill){
  return bill * 0.9;
};

Use function expressions when:

  • You want to store a function in a variable

  • You want to pass a function as an argument

  • You are working with callbacks.

Conclusion

Functions are an essential part of JavaScript because they allow us to reuse code and organize logic efficiently. Instead of writing the same code multiple times, we can define a function once and call it whenever needed. In this blog, we explored function declarations and function expressions, how they work, and their key differences such as hoisting behavior. Understanding these concepts helps us write cleaner, more maintainable, and more structured JavaScript code.

4 views