Skip to main content

Command Palette

Search for a command to run...

Function Declaration vs Expression

Updated
•4 min read•View as Markdown
Function Declaration vs Expression

May be the words sound heavier but i will try to break down these complex looking words into simpler concepts so that you don't have to struggle for rest of your life to search what they actually are !

Lets start from the beginning : )

What are functions ? Why do we use them ?

Functions are reusable block of code designed to perform specific tasks, enabling modular, organized, and efficient programming.

In programming we follow DRY ( Don't repeat yourself ) . The functions allow us to exactly do this .

lets not talk about easy looking sum function , you will not get the gist .

Here is a function railwayReservation that accepts passengers object and train details to reserve the seat for users.

function railwayReservation(passengers, trains) {
  if (Array.isArray(passengers) && Array.isArray(trains)) {
    if (passengers.length > 0 && trains.length > 0) {
      let booked = [];
      for (let i = 0; i < passengers.length; i++) {
        const element = passengers[i];
        let seat = {
          name: element.name,
          trainNumber: element.trainNumber,
          class: null,
          status: "train_not_found",
        };
        for (let j = 0; j < trains.length; j++) {
          const train = trains[j];
          if (element.trainNumber === train.trainNumber) {
            if (train.seats[element.preferred] > 0) {
              train.seats[element.preferred] -= 1;
              seat.class = element.preferred;
              seat.status = "confirmed";
            } else if (train.seats[element.fallback] > 0) {
              train.seats[element.fallback] -= 1;
              seat.class = element.fallback;
              seat.status = "confirmed";
            } else {
              seat.class = element.preferred;
              seat.status = "waitlisted";
            }
            break;
          }
        }
        booked.push(seat);
      }
      return booked;
    }
  }
  return [];
}

even if you don't understand it completely , you can get a gist .

Looking at this do you want to write this for every bookings. No right :(

There can be more complex looking task and we only want to implement it once . That's how functions are so handy .


Now lets talk about the main topic for today .

Function Declaration

defines a named function using the function keyword, followed by the function name, parameters in parentheses, and a code block in curly braces.

function greet(name) { return Hello, ${name}! }

for examples we will be looking at some easy code lines .

Function Expression

assigns a function to a variable. It can be anonymous or named

const greet = function (name) { return Hello, ${name}! } // since no name is given after function keyword therefore this is anonymous 
const factorial = function fact(n) { 
        if (n <= 1) return 1; 
        return n * fact(n - 1); 
}
// the function is named fact , this will only be accessible inside function for recursion .

Now the topic of this blog what is the difference between both

Declaration vs Expression

  1. Hoisting -Function declarations are hoisted to the top of their scope, allowing them to be called before they are defined in the code. ( will tell you what hoisting is )

  2. Function expressions are more flexible—they can be anonymous, used as callbacks, passed as arguments, and used in IIFEs (Immediately Invoked Function Expressions).

  3. Function declarations are better for standalone, reusable functions, especially when you need to call them before their definition or use recursion.

You might disagree on second and third point as they are generalized and your experience in using them might be different .

but on the first one it is how the things work around .

What is hoisting ?

in this concept , you are allowed to access the variable or function before it is initialised. If you didn't understand let me show you .

console.log( greet ) // undefined
var greet = "Hello !"

in this greet is declared later but i am trying to print its value . Now using var you can access the variable but obviously you cannot expect to get "Hello !" as till line 1 no value is given .

How is that possible ? if you try to access variables before they are declared . They are present in the memory with undefined stored .

this will not happen with let and const as they do support hoisting but do not allow to access those variables

in case of functions , when you declare the functions they are present in the memory with their whole body . therefore you are able to use them any where in the code file even above there declaration .

console.log( sum(2,3)) // 5

function sum(a,b){
     return a+b
}

as you can see i am able to use function sum above its declared line because due to hoisting the function is present inside memory with its body .


More from this blog