It is simply a collection of codes that can be used again and again rather than writing it multiple times.
You can call it whenever needed.
Example:
Suppose, in your fridge, there are some fruits like apples, kiwis and mangoes and you want to eat but only 1 at a time.
So, to eat any fruit, there are 3 steps –
1.) Open the door of the fridge
2.) Take that fruit out
3.) Close the door.
So, if we are performing these 3 things again and again, and we are performing it for apple, kiwi and mango. So, what we can do, we can create a common function for it, as there are some common actions (like open and close the door) that needs to be formed for all.
function getFruit(foodType){
var type = “”;
“open the door”;
type = foodType;
“close the door”;
return type;
}
getFruit(“apple”);
getFruit(“kiwi”);
getFruit(“mango”);