Functions in JavaScript

Read it in 8 Mins

Last updated on
11th Mar, 2021
Published
09th Nov, 2020
Views
7,728
Functions in JavaScript

In this blog we will learn more about the JavaScript functions. A function can be defined as a piece or block of code which is executed to perform a specific task. In other words, it is a group of reusable code which can be called anywhere in the program which makes the life of developers easy by eliminating the need of writing the same piece of code again and again. Functions help developers to divide larger programs into smaller chunks and also make them easily manageable. Functions allow us to define a block of code, give it a name and then execute it as many times as we want. We can define JavaScript function using the keyword function.  

Let’s explore JavaScript functions in detail. 

JavaScript Function Overview:- 

As in any other scripting and programming language, functions are one of the fundamental building blocks in JavaScript. A function is nothing but a series of statements that can be used to perform a task. In simple terms a function takes inputs and returns an output. In order to use a function, first we need to define it and then call the same. JavaScript provides us with many built in functions, for example  

alert (“Welcome to Knowledge Hut”); 
document.write(“Welcome to knowledge hut blogs”); 
Math.sqr(3); 

Generally, functions always return a value. For example, a mathematical function performs calculations on the input data and returns an output. Other functions return true/false, or text. Some functions return no value but perform a side-effect; write is one such function whose side-effect is to send text to the HTML document.  

JavaScript Function Syntax:- We use the keyword function to define a JavaScript function followed by the name of the function, and list of parameters(can be empty also) enclosed in  parentheses (). 

function functionName (parameters) { 
//your code    } 
Ex: function helloMessage(){ 
alert(“welcome to Knowledge hut”); } 
 helloMessage(); 

function with parameters:- 

function printEmpDetails(empFirstName, empMiddleName, empLastName){ 
alert(EmployeeDetails+ empFirstName+””+ empMiddleName+””+ empLastName); 
} 
printEmpDetails(“Mohandas”,”Karamchand”,”Gandhi”);àOutputàEmployeeDetails Mohandas Karamchand Gandhi. 
printEmpDetails(“William”,”Henry”,”Gates”); à OutputàEmployeeDetails William Henry Gates. 

functions with argument objects:- 

In JavaScript we can pass argument objects as default; argument object is just like an array object. 

function printEmpDetails(empFirstName, empMiddleName, empLastName){ 
alert(“EmployeeDetails”+ arguments[0]+””+ arguments[1]+””+ arguments[2]); 
} 
printEmpDetails(“Mohandas”,”Karamchand”,”Gandhi”);àOutputàEmployeeDetails Mohandas Karamchand Gandhi. 
printEmpDetails(“William”,”Henry”,”Gates”); à OutputàEmployeeDetails William Henry Gates. 
We can also iterate arguments as  
function printEmpDetails () { 
    for(var i = 0; i < arguments.lengthi++){ 
 alert(arguments[i]); 
    }} 
 
printEmpDetails(“Mohandas”,”Karamchand”,”Gandhi”); 

Function with return value:- 

By using a return statement in function it will always return zero or 1 value. 

function addition(var1, var2) { 
    return var1 + var2; 
};  var output = addition(5,15); à Output returns as 20, and assigns it to the variable output 
function square(var1, var2) { 
    console.log( var1 * var2); 
}; 
output = square(2,5); // Output does not return any value, since the variable has not been assigned to print the output. 

Function Expression:-

In JavaScript we can also assign a function to the variable and then use that variable as the function. 

var sum = function addition(var1, var2) { 
    return var1 + var2; 
}; 
var output = sum(5,15); à Valid way of calling function using variable  
var output1 = addition (5,15); à Invalid way of calling function using variable  
 Anonymous Function:-  In JavaScript we can define function without any name, this function without any name is known as an anonymous function. 
var printMsg = function (){ 
alert("Welcome to Knowledge Hut!"); 
}; 
printMsg(); àoutput will be Welcome to Knowledge Hut.  

Nested Functions:- 

 In JavaScript we can write more than one function. Nested functions will be in the scope of outer functions. Inner function will be able to access parameters and variables of the outer functions.  

function printMsg(name){ 
function something() { 
alert("Welcome " + name); 
}return something(); 
}printMsg("Gandhi"); àOutput àWelcome Gandhi. 

JavaScript Function Invocation:- 

Whenever we want to execute the code that is written inside the function, we need to invoke that function. In JavaScript we can invoke functions in 4 different ways. 

  • As a function itself. 
  • As a method, using call() and apply() 
  • Using constructor. 

As a function itself:-

 This is the basic way of calling a function. 

function print(){ 
alert(“welcome to knowledge hut”); 
 
print(); 

As a method:- 

 JavaScript provides us with predefined call() and apply() methods which can be used to invoke other functions. The major difference is apply(which takes arguments as an array, whereas call() takes arguments as one by one separately. The methods call() and apply() allow you to invoke the function, giving you a lot of control over how the function executes. 

var msg = function (str) { 
    alert("Student First Name " + this.var1 + ", Last Name" + str.var1); 
}; 
var str1 = { var1: "APJ" }; 
var str2 = { var1: "Kalam" }; 
msg.call(str1, str2);  // => Student First Name APJ, Last Name Kalam 
msg.call(str2, str1);  // => Student First Name Kalam, Last Name APJ 
msg.apply(str1, [str2]); // => Student First Name APJ, Last Name Kalam 
msg.apply(str2, [str1]); // => Student First Name Kalam, Last Name APJ 

The this keyword 

In JavaScript, this is a special keyword which is used within methods to refer the object on which a method is being called. The value of this can be determined using the following series of steps: 

  1. If using call or apply to invoke the function, this will be set to the first argument passed to call/apply. If the first argument passed to call/apply is null or undefined, this will refer to the global object. 
  2. If using bind to invoke the function, the this will be the first argument that was passed to bind at the time the function was created. 
  3. If function is being invoked as a method of an object then this will refer to that object. 
  4. If the function is invoked as a standalone function and not attached to any object, this will refer to the global object. 

Using constructor:- 

JavaScript allows us to create the function dynamically using the Function() constructor along with new operator. 

Syntax:- new Function([arg1 [, arg2 [, ...argN]] ,] functionBody) 
var sampleFunction = new Function('x', 'y', 'return x * y'); 
 console.log(sampleFunction(5,5)); àOutput = 25 
 
Adding a Method to a Constructor 
function vName(firstName, lastName, age) { 
  this.visitorFirstName = firstName; 
  this.visitorlastName = lastName; 
  this.visitor = function() {return this.visitorFirstName + " " + this.visitorlastName;}; 
} 
var visitorName = new vName("APJ","Kalam"); 
console.log("Welcome to Knowledge Hut” +visitorName.visitor()); 
outputà Welcome to Knowledge Hut APJ Kalam 

Built In Constructors:- 

var a = new Date(); //new date object 
var b = new String(); //new String object 
var c = new Function(); //new function object 

JavaScript Function Parameters: -  When we invoke a function we can pass some parameters to the function. These parameters are used inside the function and we can pass as many parameters as required, separated by commas. 

function functionName(parameter1, parameter2,…, parameterN) { 
  // your code to be executed 
} 

General rules for JavaScript parameters. 

  • We do not specify any datatype to the parameters. 
  • There is no type checking on the parameters passed. 
  • No restrictions on number of parameters passed. 

JavaScript also has argument object which is known as built-in object. Whenever a function is invoked the argument object which is an array of arguments can be used. 

var a = add(10,20,23,40); 
function add() { 
  var x; 
  var add = 0; 
  for (x = 0; x < arguments.length; x++) { 
    add += arguments[x]; 
  } 
  return add; 
} 

How to close Functions:- 

JavaScript function closures are very important as they will control what is there and what is not there in the scope of the function. Closures are very important and frequently used in JavaScript for data privacy. Mainly it is used while handling events and call back functions. With the help of closures, inner functions have access to the enclosing/outer functions variables. 

function out() { 
   var y = 10; 
   function inn() { 
          var x = 20;  
         console.log(x+y); 
    } 
   return inn; 
}   

In the above example, we have defined two functions in and out. An out function has been defined with a variable y and it returns the in (inner) function. Whereas in function has its own variable x and accesses the out variable y in the function body. Here the scope of the out variable is limited to out function; similarly the in function is limited to inner function. Now you may wonder, how does the in function access the y variable defined in the scope of the out function? This is where the closure comes into picture in JavaScript. With closure, the inner function always gains access to the variables and parameters defined in the outer function, even after the outer function has returned. Closure is a function that always remembers the variables from the place where it is defined, regardless of where it is executed later. 

Conclusion:-

In this blog we have discussed about JavaScript functions which are blocks of code and are executed repeatedly. Function helps us to avoid repeating the same code all over the place. You can use a function to wrap that code and reuse it. Functions can take zero or more than one argument. Since JavaScript is a loosely coupled language, we can pass any value to any of the data types and it is always optional to specify the parameter value while invoking the functions. Functions are the foundation of a good JavaScript programmer. Using them makes your programs better organized, clearer, more readable, and easier to understand when you wrap your code up in well-named functions for reuse. 

Profile

KnowledgeHut

Author
KnowledgeHut is an outcome-focused global ed-tech company. We help organizations and professionals unlock excellence through skills development. We offer training solutions under the people and process, data science, full-stack development, cybersecurity, future technologies and digital transformation verticals.