A brief introduction to Functions in JS

A brief introduction to Functions in JS

Before starting the blog about the function, I just want to say that the "functions in the JavaScript are the heart of JavaScript". The function in JavaScript are way beautiful than the function in any other programming language, so let's start the exploration of the functions in JS.

What is function?

Function is a collection of statements, which are used to perform a specific job or task in a JavaScript program.
Let's have a look of how a function looks in JS:-

function sum (number1, number2){
      console.log(number1 + number2);
}

Syntax of a Function

Before knowing the explanation of the above code, let's try to understand the syntax of a function in js. The first thing we have to use is the keyword function to create the function after which we have to mention the function name which can be any name according to your choice, then we uses parenthesis in which we can pass some parameter about which we will talk later. Finally we uses curly braces to enclose all the statements within the function body, these curly braces also defines the body of the function.
Let's have a look at the below image to make things more clearer.

img1.png

Invoking or Calling a Function

Creating a function does not means that it will run automatically, it will run only when that particular function is called or invoked (called and invoked both are same). Once a function is invoked, it will start it's execution of all the statements within it.
Have a look at the below code:-

function sum (number1, number2){
      console.log(number1 + number2);
}

// Calling the Function
console.log(sum (10, 20)); // 10 and 20 are arguments here

Parameter and Argument in a Function

Most of the people uses these two word interchangeably which is not correct. This two has their own meaning and usage to which we know in this section, but never use them interchangeably because they are different.

Parameter:- Parameter are the variables which are defined at the time of function definition. These are enclosed within the parenthesis and their scope is within the function itself.
Argument:- These are the actual value which are passed to a function when we call a function and these values are given to the parameter.

img2.png

Working of Function in JS

We can understand this one by taking a sample code example, which is given below:-

let x = 10;
console.log(x);

function a(){
  let x = 20;
  console.log(x);
}

function b(){
  let x = 30;
  console.log(x);
}

a();
b();

// Output
// 10
// 20
// 30

Let's try to understand the execution of this code line by line by it's execution context and call stack so that we can have a clear idea over this one.
Step 1:- In the first go, as we know the scanning of the code will be done, in which the JS engine will allocate the memory to all the variables and functions and with that the global execution context will be created and pushed in the call stack as shown in the below image. At the time of scanning the variables are assigned with a special value called "undefined" and the function's reference are provided there which means they will be available as they are in the memory. img3.png Step 2:- Now the first line of code will be executed and the value of "x" will be assigned to it in the memory and the undefined will be removed. After which the line 2 will print the value of "x" in the console which will be 10 as it is in the memory. img4.png Step 3:- Now the JS engine will ignore the function a and function b as they are not being called.
On the bottom side the a function will be called and a new execution context will be created in the call stack and again the scanning of that function will be done then the execution of that function will start. img5.png Step 4:- Now the engine will execute the function a line by line and will assign a value of 20 to the variable x. After this the logged value in the console will be 20 as it is available in the local scope, if it was not available in the local scope then the engine will search for it in it's parent scope (lexical scope). img6.png Step 5:- Now the execution of function a will be completed and it will be popped out from the call stack and it's execution context will also be deleted from the memory. img7.png Step 6:- Now the function b is called then the execution context of it will be created and will also be pushed in the call stack, it's memory assignment will also be done as it was for the function a. img8.png Step 7:- Now the execution of the function b will be started and the value of x will become 30 and in the line after it, the value will be logged which will be 30 as it is available locally in the memory. If we assume that the value of x was not available in the local scope then it will access the value from it's lexical scope means from the global value and the value of x will be 10 then. img9.png Step 8:- Now the execution of function b will be completed and the execution context of function b will be deleted and it will also be popped out from the call stack. img10.png Step 9:- Now the execution of whole code is done then the global execution context will also be deleted and will also be popped out from the call stack and the call stack will be empty and the execution of code will stop now.

Hoisting in the Function

When we try to access a variable or a function in a program before it's declaration then this is known as Hoisting.
In JavaScript we can perform hoisting with a function, which means we can access a function (call a function) before it's declaration in the program.

sum(10, 20);

function sum(a, b){
    console.log(a+b);
}

Function Statement / Function Declaration

It is the way of creating a normal function. The function to which we have created as of now in the blog is function statement or function declaration which has given a fancy name now.

function sum(num1, num2){
  console.log(num1 + num2);
}

Function Expression

When we assigned a function to a variable as a value then this type of function is known as a function expression.

let a = function() {
    console.log("function expression");
}

As in the above example I am assigning the function to the variable a as we assign value to the variable.

Difference between the Function Statement and Function Expression

As we can see that we can define a function using the function statement and function expression both, but we need to understand that both the ways are different and behaves differently while execution.

Note:- Hoisting is the main difference between the function statement and function expression.

Let's dig a little bit by taking a simple example of the above condition to understand it in a better way.

sum(10, 20);
sub(20, 10);
function sum(num1, num2){
  console.log(num1 + num2);
}

let sub = function(num1, num2){
  console.log(num1 - num2);
}

If we will run this program then it will first add the 10 and 20 because the sum function is available there but when it will try to execute the sub function then it will throw a error that the function is not defined because at the time of scanning phase the function sum will be assigned a memory but the sub will be treated as a variable and will be assigned with undefined until the code execution reaches the sub variable execution.
Therefore the hoisting is possible easily in the function statement but will not work for the function expression as it will be treated as a variable and the function will be assigned to it only when the code execution of that will happen.

Anonymous Function

Any function which is without the function name is considered as the anonymous function. As we have learnt that we have to mention function keyword, function name in order to create it but in this scenario there will not be any function name.
Let's take an example-

function (){
  console.log("I am an anonymous function");
}

Note:- If we will run this code then it will throw an error because we can not define a function without it's name in the JavaScript, therefore it will throw a syntax error.

According to the above scenario we can not use an anonymous function, so there is a question that where it will be used, then the answer for this is the function expression in which we uses anonymous function.

let a = function(num1, num2){
  console.log(num1 + num2);
}

a(); // Calling the function

Note:- Here we can see that we had used the anonymous function to create the function expression.

Named Function Expression

As the name suggest, it is similar to that of function expression but have an additional functionality in it. In function expression we uses anonymous function to create it but in the case of named function expression we do not uses anonymous function in that. Instead of anonymous function we uses proper function to create having a function name as given in the below example-

let a = function sum(num1, num2){
  console.log(num1 + num2);
}

a(); // Calling the function

Note:- We can call the above function by using "a" but will not be able to invoke it by using "sum", because "sum" will only be accessible when we will invoke it within the sum function.

First Class Function

First Class Functions are also known as the First Class Citizens. This is a special ability of a function in which we can pass a function in another function as a argument and can also return a function as a value from a function.
This is quite amazing for anyone who is from another programming language background where it is not possible, but in JavaScript it is possible.
In other word, we can say that the first class function is the functionality in which we can use a function as a variable and can pass it as a value or can return it like a value.

function morningGreet() {
  return "Good Morning";
}

function welcome(morning, name) {
  console.log(name + " " + morning() + "\nWelcome to the Office");
}

welcome(morningGreet, "vinay");

/*
vinay Good Morning
Welcome to the Office
*/

In the above given code we can easily see that the welcome function has an argument morningGreet which is also a function passed as an argument in it.

function greet(){
    return function(){
        console.log("Good Morning Everyone");
    }
}

// greet has nothing to print as the console.log is in the function
greet();

// to run that function we can use double parenthesis ()()
// first parenthesis for greet function and 
// second for the return function to execute
greet()();
// Output: Good Morning Everyone

In the above given code we can see that the function greet is returning a function as value from itself.

Call Back Function

As we have discussed that the function in JavaScript are the First Class Citizens which means we can pass a function as an argument to another function and can also return a function from a function as a value.
When we pass a function as an argument to another function then the function which is passed as an argument is called a call back function.

function morningGreet() {
  return "Good Morning";
}

function welcome(morning, name) {
  console.log(name + " " + morning() + "\nWelcome to the Office");
}

welcome(morningGreet, "vinay");

In the above given code the morningGreet is a call back function which is passed as an argument to the welcome function.

call back functions are mainly used to unlock the asynchronous ability of the JavaScript.
As we know that the JavaScript is a single threaded synchronous programming language which can executes only one line of code at a time line by line but by using call back function we can perform asynchronous job in JS.

setTimeout and event listener are the best example of callback function which are used for asynchronous programming in JS.

setTimeout(() => {
    console.log("Asynchronous Property");
}, 5000);

In the above example, I have passed a function as argument inside the setTimeout whose body will start executing once the timer of 5 second is over, until which other lines of code will be executed as JavaScript does not wait for any line of code to execute.
That's the reason for a famous saying that the "JavaScript does not wait for anyone".

HOF (Higher Order Function)

In JavaScript, a function which accept function as a parameter or it return a function as a value then that function is known as Higher Order Function. For ex: The function which is using a call back function is a Higher Order Function because it is passing a function as a argument in it.
The popular setTimeOut, setInterval are a better example of the HOF.

Thanks for reading till the end, hope you had learnt something and enjoyed it, if so let me know by commenting and give it a like to motivate me.