All about JS function

All about JS function

JavaScript is dynamic type language but without function approach JS is useless.This article is for beginner to advanced level JS developers.

Programming is a way to convert your ideas into machine code OR it is a thought that transform into certain rules. There are many features available in programming languages like, variables, objects, arrays, loops, conditions, function etc, same case with JS. But our entire focus will render only on function. After reading this, you will be able to play with functions. Let's play together.

What is a function in JS?

Let's understand first the theory behind function. Basically, a function is like a pre-planned event, to make it more simple we are going to take real-world example. Suppose you are a student in a college and after one week there is a farewell party for your last batch so, you must make some arrangement like you maybe buy some new clothes or some new belongings or maybe you might trying to prepare for farewell speech and etc. There is one thing common that is arrangements or pre-plan. So, we have found here two major things, one is a farewell party and second is arrangements/pre-plans. Now, both farewell party and arrangements/pre-plans are relative to each other, if there is no farewell then you might not buy/prepare for anything, right! There is same approach in programming world, suppose you want to make an event which handles two integer values by multiplying them, now here, we need a function to make things work so, again what is a function

a function is just like an event and logical code inside function body is just like arrangements

function multiply(a,b){
     const result = a*b; //arrangement 1
     console.log(`The multiplication of ${a} and ${b} is: ${result}`) 
     //arrangement 2
}
multiply(3,5);// event->calling
//output will be,
//The multiplication of 3 and 5 is: 15

Now, look at above simple code where we can see comments, the declaration of a function where we have multiplied two integer values and printing them inside console.log() is like pre-planning/arrangements and after calling a function named multiply(3,5) is just like a event. if we do not call the function then it will never run. In technical point of view, while declaration of a function needs a set of rules for execution and calling/invoking a function is a event call.

function multiply(a,b){
     const result = a*b; //arrangement 1
     console.log(`The multiplication of ${a} and ${b} is: ${result}`) 
     //arrangement 2
}

Now in above code, I have defined/declared a set of rules now machine knows what to do but it don't know when to do, without invoking/calling a function it is not possible to run it.

So, this was just overview that what exactly a function is now,

What are required tools/rules for a function?

There can be many tools/rules for the function but the basics are,

  1. Declaring a function
  2. Calling a function
  3. Return something

Declaring a function

const userInfo = { //dummyObject
   username: "Fahad Khan",
   age: 24
};
function getUserInfo(info){ //declaring a function
const {username, age} = info; // objcet destructuring
console.log(`Name: ${username} and ${age} years old!`);
}

Calling a function

getUserInfo(userInfo);//invoking

Return someting

const userInfo = { //dummyObject
   username: "Fahad Khan",
   age: 24
};
function getUserInfo(info){ //declaring a function
const {username, age} = info; // objcet destructuring
return`Name: ${username} and ${age} years old!`; //return string
}
const showInfo = getUserInfo(userInfo); //function returns to showInfo
console.log(showInfo); //Name: Fahad Khan and 24 years old!

Now things are going to a bit complex, due to return keyword the structure of a function declaration and calling function become changed as you can see above that we didn't console.log() anything instead we've used return keyword because we want to send a output. now, we can return any kind of data as we want inside function.

const transaction = [1200, 5000, 1000, 40000];
function totalNumberofTransactions(array){
console.log(array.reduce((accumlator, currentValue) => { 
accumlator + currentValue
}));
return array.length;
}
const result = totalNumberofTransactions(transaction); 
console.log(result)

here, we've returned a number value instead of returning string value like we've done before. It might be possible the above code may look difficult to understand for newbie. Now, the above code will only shows 4 in output but we will never see the output of console.log() inside a function where we've written array.reduce() method just because of not including return keyword. if we write return keyword inside function console then will see like this,

const transaction = [1200, 5000, 1000, 40000];
function totalNumberofTransactions(array){
console.log(array.reduce((accumlator, currentValue) => { 
return accumlator + currentValue;
}));
return array.length;
}
const result = totalNumberofTransactions(transaction); 
//result has return array.length value

console.log(result)
//this will show 
// 4 
//47200 console value

we can return anything like object, array, function, number, string etc.

function A(){
return {name: "Fahad Khan",age: 24} //you can return an object
}
function B(){
return functionAB(){return "Hello"} // return string
}
function B(){
return functionAB(){return 2*2} // return number
}

One point is very important if you use return keyword it means you want output from a function and for receiving output you must have to store a value before using it. example

function A(){
return {name: "Fahad Khan",age: 24} //you can return an object
}
function B(){
return functionAB(){return "Hello"} // return string
}
function B(){
return functionAB(){return 2*2} // return number
}


const resultA = A(); //now return value is saved in resultA 
const resultB = B(); //resultB has return string value which is "Hello"
const resultC = C(); //same case

It should be noticed that whenever you want to call a function then we must use () parenthesis otherwise function can't be called. Now, we know how to declare a function and how to call() a function and finally how return keyword works.

New way of function declaration In modern JS, things become advanced and changed! the way of function declaration we've learnt is too old now ECMAScript 2016 (ES6) is on ground so JS developers has introduced new way for declaring a function which is arrow function. It is not difficult to understand,

function sumTwoNumbers(a,b){//old syntax
return a+b;
}


const sumTwoNumbers((a,b) => a+b); // arrow function

if we've single statement (a+b) like in our case then it is not mandatory to use return keyword if you have multiple statements then it is required because machine dosen't know which statement should be return.

Now you can make more powerful function called Constructor Function

function user(name, age){
this.name = name;
this.age = age;
}
const info = new user("Fahad", 24);
info();

this is the constructor function which can help you to make unlimited copies of your declared code with new keyword. What is Constructor Function

Finally, it was all about JavaScript function that how to declare, modify, call, return and make new copies of a function. Make sure that you can use only one return statement inside a function. Hope you enjoyed this. Any question regarding this is welcomed. Thanks.