Sitemap

Heart of JavaScript

3 min readApr 23, 2024

--

Hey There! Today we are going to cover in detail the heart of JavaScript. Any guesses?? Let’s get started to know what it is….

Press enter or click to view image in full size

Today we are going in details of Functions. Yes, Functions are the heart of JavaScript. There are different terminologies in functions, we will cover them with examples so that it is easy to understand.

Function Statement:

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

The above way of creating a function is called function statement. This is also known as function declaration.

Function Expression:

var b = function (){
console.log("b called");
}
b();

When function acts like a value which we use to initialize, it is called function expression.

So now the important question that comes up is what is the difference between the above two i.e., function statement and function expression?
Answer to it is Hoisting. If we call these functions before creating them, it will throw an error for ‘b’. As in the memory creation phase ‘a’ is assigned a memory and ‘b’ is treated as a variable.

Anonymous Function:

The functions which don’t have their own identity. For example,

function (){
}

The above statement will give syntax error because it doesn’t have a name. They are used in a place where functions are used as values. Correct example will be,

var b = function (){
console.log("b called");
}
b();

Named Function Expression:

Get Neha Prabhakar’s stories in your inbox

Join Medium for free to get updates from this writer.

It is same as function expression just we use the named function instead of anonymous function.

var b = function xyz(){
console.log("b called");
}
b();

Now let’s look at a corner case for the named function expression:

var b = function xyz(){
console.log("b called");
}
b();
xyz();

Now if we call xyz() method, what do you think will happen? It will give a Reference error mentioning xyz() not defined. This happens because it is not defined in the global scope.

Quick Note :
function b(param1, param2) -> these are the parameters
b(2,5) -> these are the arguments

First Class Functions:

The ability to use functions as values is called first class functions. We can pass functions as arguments also can return the functions.

var b = function(param1){
console.log(param1);
}
b(function(){
});

Below will be the output :

var b = function(param1){
function xyz(){
}
}
b(xyz);

Below will be the output :

Example of returning a function from a function:

var b = function(param1){
return function(){
}
}
console.log(b());

Below will be the output :

First Class Functions are also known as First Class Citizens.

Hope this was helpful and easy to understand. If you found this blog helpful please go through my profile and have a look at some other interesting content. See you in next one! :) Until then..

Press enter or click to view image in full size
Photo by Etienne Girardet on Unsplash

--

--