What is a function in Javascript and how do we use it?

September 15,2020 - 12 min read
what is function in javascript

JavaScript is an object-oriented programming language used for creating interactive web pages. It is an event-driven, functional and imperative language. It is popularly used to make dynamic effects on web pages like rollover, rollout and other interesting functionalities. Javascript was initially used for browsers and web pages but now it has diversified and has moved to other environments and applications also.

In this article, we are going to talk about a distinct feature of the Javascript language that helps developers to build complex applications with ease. Javascript functions are useful and efficient features that come handy while developing lengthy pieces of code.

Javascript functions

A JavaScript function allows you to define a block of code, give it a name and then execute it as many times as you want. A JavaScript function can be defined using the function keyword.

As we mentioned above, function is a piece of code that is specially designed to perform a specific task. Here is the basic syntax of functions in Javascript.

  • function functionName(){
  • //Run this code (Run this code if the function is called)
  • }

There are several evident advantages of Javascript functions. One of them is code reusability. With functions you write a particular code only once and simply call it every time you want to reuse the code. Once you create a function for a task, it can be used whenever the task is required.

This way, the code is only written once but used several times in a particular application. Code reusability saves time and makes the program compact, readable and efficient.

Implementing Javascript Functions

Functions in JavaScript (and in all other computer languages) have parameters in the function definition itself. But arguments are the real values that are passed during the function calling.

You can pass values to a function. These values are called arguments. To receive arguments, the function has variables called parameters. In other words, you can pass an argument by calling a function like functionName(arguments). When the function is called, the passed arguments are assigned to the parameters and used inside the function. The following is a simple syntax of function with argument in JavaScript.

  • function add(num1,num2){
  • var res =num1+num2;
  • return res; }
  • var r = add(7,8)
  • console.log(r);

In the above code, num1 and num2 are parameters. 7 and 8 are arguments. While the function is defined, we pass variables num1 and num2 called parameters and while the function is called the actual values to be used in the programme are 7,8 and are called arguments. The Output of this program would be generated when the last statement that is console.log(r) is executed. Another interesting point to note is that here, the return value of the function is stored in a variable.


15(It is a simple addition of two numbers )

As mentioned in the above example, you can pass an argument by calling a function example functionName (arguments). When the function is called, the passed arguments are assigned to the parameters and used inside the function.

In the below example, "Rahul" is a string argument which is assigned to the function as arguments. This function joins the parameter to other strings given inside the function.

  • function intro(myname){
  • console.log("Print","Hello " + myname + ", Welcome to Konfinity!") //function definition
  • }
  • intro("Rahul"); //function calling

Print Hello Rahul, Welcome to Konfinity!

In simple words, here is a quick summary of declaring, defining and calling functions.

  • Declare a function and add parameters.
  • Write code inside the function to execute //defining the function
  • Call function with suitable argument

Multiple Arguments in Javascript Functions

Till now, we have covered Javascript functions with single arguments and parameters. Now we would see in detail Javascript functions with multiple parameters and arguments. You can add multiple parameters to a function and arguments by separating them with a comma (,). The order of the arguments must match with the order of the parameters so that arguments can be passed to correct parameters inside the function. The syntax of Javascript functions with multiple arguments is given below.

  • function multiple_arg(var par1,var par2,var par3){
  • //code to be executed}
  • var output = multiple_arg(arg1, arg2,arg3); // calling the functions.

Return Statement in Javascript Functions

You can send the output value of a function to the place where the function is called using the return statement. Any line of code written after the return statement is not executed. A simple syntax of return statements in Javascript functions is given below.

  • function ret(var a,var b,var c){
  • return(a+b);
  • }

In the example below, we have created a function to calculate the product of 2 parameters and send the result using the return statement. When the function is called with arguments, the return value replaces the caller function and is assigned to the output variable.

  • function multiply(a,b){
  • var product = a*b;
  • return product;
  • console.log(a+b) //This statement is not executed
  • } var output = multiply(10,15);
  • console.log ("output is", output);

Output is 150.0

We have covered the basics of Javascript function. The concept, need and implementation are explained and now we would come to more complex but interesting dynamics of Javascript functions.

Variables in Javascript Functions

Variables declared inside the functions are called local variables to that particular function. These variables cannot be used outside the scope of the function. Take a look at the example below to get a clearer picture.

  • function Konfinity (){
  • let message = " Konfinity is a place to make a lucrative career in technology";
  • alert (message);
  • }
  • Konfinity ();.
  • alert (message);

In this code, we could get an alert box with the message "Konfinity is a place to make a lucrative career in technology", because we have called the function Konfinity (). But the next line is prone to error as the variable message is used outside the scope of the function. Message is a local variable which can only be accessed inside of the function it is declared.

Another type of variable is the Global variable. Variables accessed outside the scope of a function are called global variables. These variables can be accessed anywhere in the code. The main difference between local and global variables is that unlike local variables, the use of global variables is not restricted to the scope of a particular function. We would change the previous example to understand the concept of global variables.

  • let message = " Konfinity is a place to make a lucrative career in technology";
  • function Konfinity ()
  • {
  • alert (message);
  • }
  • Konfinity ();.
  • alert (message);

In this code, we would get to similar statements, i.e the output of this code would be -


Konfinity is a place to make a lucrative career in technologyKonfinity is a place to make a lucrative career in technology

This happens because in this particular code, the variable message is declared and initialised outside the function and hence can be accessed anywhere within the program.

Global variables are used to store project level data. But mostly, programmers make use of local variables while developing their code.

Nested Javascript Functions

Nested Javascript functions are functions that are defined within another function. The nested function (that is defined inside another one) cannot be called independently. That means that the nested function is private to the outer function. Following the tradition, let’s learn nested Javascript functions by example.

  • function introduction (Name, lastname){
  • function message()
  • {
  • return Name + “ “ + lastname;
  • }
  • alert (“Hello, “+ message ());
  • alert (“Welcome to Konfinity, “+ message() );
  • }

Here message() is the nested function while introduction is the main Javascript function. We also saw an interesting concept here that even nested functions can be returned. The functions can be returned in two ways- as a property of a new object or as a result by itself. Javascript nested functions are created for the convenience of programming complex applications.

Built-in Javascript functions

Javascript has a bunch of in-built functions. It actually means that you don’t have to define the function but just call them when required. Here is a list of some useful built-in Javascript functions that can come handy the next time you sit to build Javascript applications.

Recently, there has been an addition of a number of Javascript functions that work particularly for objects, arrays and strings. Let’s have a glance at each one of them and understand their uses.

Objects in Javascript allow you to group different data types. There are various built-in methods for objects like assign (), entries () and getOwnPropertyDescriptors (). The function assign () can copy, clone and concatenate two or more objects. The second in line, entries () return the keys and values in the form of an array. getOwnPropertyDescriptors () gives the properties descriptor for an object.

There are a bunch of built-in methods that can be used with Arrays. Some of them are includes (), find (), findIndex() and many more. Includes () check for the existence of any property in an array. Find (), as the name suggests, finds any element in an array and findIndex does the same thing but returns the Index instead of the value.

The new addition to Javascript built-in methods for strings are repeat () and includes (). Repeat () allows you to repeat the string as many times and includes () checks for the existence for a particular string.

Apart from these built-in methods that are specific to a particular data type, there are other Javascript built-in functions in Javascript also.

One such function is eval (). This built-in Javascript function evaluates the code that is represented as string. The obvious second in this list is uneval (). The function of uneval is to create a string representation of the source code of the object.

Next function in line is isFinite(). This function checks for infinity in the parameter passed. It determines if the value is a finite number, it also first converts the parameter to a number if required. There are a number of built-in functions which return a number of particular data type.

Another interesting methods are decodeURI() and deodeURIComponent(). These functions basically decode a Uniform Resource Identifier (URI). Other Javascript functions such as encodeURI() and encodeURIComponent() are also built-in Javascript. They basically encode a Uniform Resource Identifier (URI) by replacing each instance of certain characters by escape sequences representing the UTF-8 encoding of the character.

Another type of built-in javascript functions are the escape () and unescape() functions. In the escape() function, the methods basically compute a new string in which certain characters have been replaced by hexadecimal escape sequences. The unescaped () function does exactly the opposite, it computes a new string in which hexadecimal escape sequences are replaced with the character that it represents. The function unescaped is a deprecated function so an escape sequence can be generated by the function escape ().

With this, we have comprehensively understood Javascript functions. However, there without practical implementation, the knowledge of Javascript functions is incomplete. We urge you to develop an application in Javascript using the basic concepts of functions, nested functions and built-in Javascript functions.

Developers still across the world rely on Javascript to create a dynamic experience for the users. It is one of the most popular languages in web development. If you see yourself as a web developer then a deep knowledge of Javascript is essential.

In case you didn’t know, Konfinity ‘s Web Development Course is developed by experts from IIT DELHI in collaboration with tech companies like Google, Amazon and Microsoft. It is trusted by students and graduates from IIT, DTU, NIT, Amity, DU and more.

Join the course to master the art of creating web applications by learning the latest technologies, right from basic HTML to advanced and dynamic websites, in just a span of a few months.

Konfinity is a great platform launching a lucrative tech career. We will get you started by helping you get placed in a high paying job. You know what’s amazing - no prior coding experience is required to take up our courses. Start your free trial here.