Functions are the heart of Javascript πŸ’˜ !!

Functions are the heart of Javascript πŸ’˜ !!

Β·

5 min read

Functions are the heart of Javascript πŸ’˜ !!

We often need to perform similar actions in many places on our website. An example of that would be a greeting message when a user logs in or logs out.

This is where we can make use of functions and invoke them wherever required.

The simple way to do this is by creating 2 functions namely greetUserOnLogin( ) and greetUserOnLogout( )

The above solution is completely fine but it is against the DRY(Don't Repeat Yourself) principle as we are performing the same action but with two separate functions.

So, can you think of a better way?

Think

Yes, there is a better way to do it by declaring just one function and calling it by passing an argument based on the loggedIn/loggedOut status of the user.

Before I show you the code to do that, let's cover the basics of functions and at the end of this blog, you can find the solution.

Let's dive deep into some of the basic terms which we should be knowing about functions.

dive

0. Javascript Function Anatomy

function Name.png

1. Function Declaration aka Function Statement

A function statement is nothing but the keyword function followed by the function name and the block of code. Here is the syntax -

function printMessage( ) {
    return "Hello world 🌏";
};

// function printMessage is invoked/called as follows.
printMessage( ); // Hello World 🌏

In the above code, printMessage is a function which when called, prints "Hello World 🌏"

2. Function Expression

let printMessage = function( ) {
    return "Hello World 🌏";
};

// function printMessage is invoked the same way as function declaration.
printMessage( ); // Hello World 🌏

3. Difference between Function Expression and Function Declaration

The main difference between the two is that function expression can be called before declaring the same whereas the same is not possible in the case of a function declaration. This is because the way variables (declared with var) and functions are hoisted in javascript.

A quick detour - How hoisting works in javascript?

So when a script runs, the JS engine runs the code in two phases -

  • Memory creation phase
  • Code execution phase.

First, the memory creation phase runs in which memory is allocated to all the variables & functions. It will allocate undefined to variables(declared with var) and save the whole function body for functions.

After the memory creation phase, the code is executed line by line. In this phase, the actual value which is assigned is allocated in place of undefined.

When we access a variable (which is declared with var) before initializing the same, we will get undefined.

In a function declaration, we assign a function to a variable. if we try to access it before initializing, we will get an error because it has undefined stored in the memory and hence we cannot invoke a variable that is undefined.

If it is not clear, check the below code -

// Hoisting in Javascript

// accessing before initialising

a( ); // Hello
console.log(b); // undefined;

function a( ) {
   console.log("Hello");
}

var b = 10;

// accessing after initializing, the var b will be allocated 10 as the value.

a( ); // Hello --> Same behaviour
console.log(b); // 10

In case you want a detailed explanation of hoisting, check my detailed blog on hoisting

// Function expression and Function Declaration

printMessage( ); // "Hello World 🌎"
printMessage2( ); // TypeError printMessage2 is not a function.

function printMessage( ) {
  console.log("Hello World 🌎");
};

var printMessage2 = function( ) {
  console.log("Hello World 🌎");
}

I hope you understood all the things up until now. It can be too much to take it up all at once. If anything is not clear, I would suggest to re-read and coding it out to get the hang of it.

dontPanic

Please don't panic and let's continue...

4. Named Function Expression

A named function expression is the same as a function expression but has a name instead of an anonymous function.

var printMessage = function greetWorld( ) { // Named function expression
  console.log("Hello World 🌎"); 
};

printMessage( ); // Hello World 🌎
greetWorld( ); // throws Reference error: greetWorld is not a defined.

We assign a name to a function expression so that it is easier to debug. The console would print the name of the function if there is any error while calling the function expression.

5. Parameters and Arguments

WhatsApp Image 2022-05-14 at 11.27.22 AM.jpeg

6. What are first-class functions?

Functions in javascript are first-class citizens because of the following qualities -

  • We can pass functions as arguments to other functions and/or return a function.
  • The function which returns another function is called Higher-order-function(HOF).
  • The function which is passed as an argument to another function is called a callback function.

These qualities make functions first-class citizens. It is a programming concept that is available in other languages too.

// Normal function which console logs a message
function greetWorld(){
   console.log("Hello World 🌎");
};

function printMessage(callback) {
   //  callback function called
   return callback( ); 
};

// printMessage is HOF which takes a callback function and returns it.
// greeWorld is the callback function

printMessage(greetWorld); // Hello World 🌎

I hope now you can appreciate why functions are the heart of javascript πŸ’˜.

End

Reference

Akshay Saini's Namaste JS series

Before I take leave, here's the solution to the first problem which I mentioned at the beginning of the blog.

You can create a function and name it greetUser which accepts loggedIn/loggedOut status as a parameter.

function greetUser (userStatus)  {
    if(userStatus === "loggedIn") {
        alert("Hello User, it is good to see you back πŸ€—");
    } else if(userStatus === "loggedOut") {
        alert("Bye User, it is sad to see you leave😒 ");
    };
};

greetUser("loggedIn"); // Hello User, It is good to see you back πŸ€—

That's all for this blog now. In case you have any doubts, please do comment below.

Hope you liked the blog. Stay tuned for more :)

If you are reading this, thank you for reaching the end of the blog. If you liked this blog and want more such content, let me know the topics by writing in the comments. Also, you can reach out to me on Twitter.