Javascript Functions

A stack of code that can be reused by a Programmer and can be referenced from anywhere in your program is known as a Function. This defeats the need for programmers to write code more than once.

JavaScript, like every modern programming language, has all of the capabilities required to construct modular code via functions. You've probably encountered methods like write() and alert() in previous chapters. We were utilizing these functions often, although they had only been defined once in core Js.

JavaScript also allows us to create our own functions. This article will teach you about JavaScript functions, how to build your own custom functions, as well as how to apply them. To follow the pace of this tutorial, you should be conversant with certain essential Js concepts like variables, conditional statements, and expressions.

Advantages of Using Functions in Javascript

  • Functions are useful for limiting the variables' scope.
  • Closure is implemented via functions.
  • Callbacks are also implemented using functions.
  • In Js, functions are also handled as objects.
  • It is less Complex
  • It is more readable
  • It is more generic

Syntax

<script type = "text/javascript">
<!--
function functionname(parameter-list) {
statements
}
//-->
</script>

Example

<script type = "text/javascript">
   <!--
      function sayHello() {
         alert("Hello TechStack");
      }
   //-->
</script>

Function Parameters

A function can have more than one arguments sent in by the calling code and can be utilized within the function. Due to the fact that Js is a dynamic type language, these function arguments are allowed to have any values of data types.

Example

Consider the following example. Here, we've adjusted the sayHello function. It now requires two parameters.

<html>
   <head>   
      <script type = "text/javascript">
         function sayHello(surname, age) {
            document.write (surname + " is " + age + " years.");
         }
      </script>      
   </head>
   
   <body>
      <p>Click this button to call this function</p>      
      <form>
         <input type = "button" onclick = "sayHello('Milo', 12)" value = "Say Hello">
      </form>      
      <p>Use other parameters in the function and then try it out...</p>
   </body>
</html>

Calling a Function

To call a function later in a script, write the function's name as demonstrated in the code below.

<html>
   <head>   
      <script type = "text/javascript">
         function sayHello() {
            document.write ("Hello Techstack!");
         }
      </script>
      
   </head>
   
   <body>
      <p>Click this button to call this function</p>      
      <form>
         <input type = "button" onclick = "sayHello()" value = "Say Hello">
      </form>      
      <p>change the text in write method and then try it out...</p>
   </body>
</html>

The Arguments Object

By default, all Js functions can make use of argument objects. Every parameter's value is reserved in an argument object. This is very similar to an array. The values can easily be accessed by the use of an index, similar to an array. But,  It does not have support for array methods.

Example

function ShowMessage(firstName, lastName) {
    alert("Hello " + arguments[0] + " " + arguments[1]);
}

ShowMessage("Elon", "Musk"); 

ShowMessage("Hillary", "Clinton");

ShowMessage(100, 200);

Even if the function does not have any parameters, the Arguments object is still acceptable.

Example

function ShowMessage() {
    alert("Hello " + arguments[0] + " " + arguments[1]);
}

ShowMessage("Elon", "Musk"); // display Hello Elon Musk

The for loop may be used to iterate through an Argument object.

Example

function ShowMessage() {

    for(var i = 0; i < arguments.length; i++){
        alert(arguments[i]);
    }
}

ShowMessage("Elon", "Musk"); 

The return Statement

A return statement is an optional part of a JavaScript function. As an example, feed two integers into a function and expect such function to return the multiplication within your calling program.

Example

Consider the following example. It describes a function that picks two parameters and links them together before returning the result to the calling program.

<html>
   <head>  
      <script type = "text/javascript">
         function concatenate(surname, lastname) {
            var full;
            full = surname + lastname;
            return full;
         }
         function secondFunction() {
            var result;
            result = concatenate('Elon', 'Musk');
            document.write (result );
         }
      </script>      
   </head>
   
   <body>
      <p>Click this button to call this function</p>      
      <form>
         <input type = "button" onclick = "secondFunction()" value = "Call Function">
      </form>      
      <p>Change the parameters in the function and try it out...</p>  
  </body>
</html>

Nested Functions

A function in Js can contain more than one inner function and these are referred to as nested functions.

function ShowMessage(lastName)
{
    function SayHello() {
        alert("Hello " + lastName);
    }

    return SayHello();
}

ShowMessage("Elon");

Anonymous Function

We can define a function in Js without giving it a name. The nameless function can be called an anonymous function. A variable has to be given to an anonymous function.

var showMessage = function (){
    alert("Hello TechStack!");
};

showMessage();

var sayHello = function (lastName) {
    alert("Hello " + lastName);
};

showMessage();

sayHello("Elon");

Js Function Methods

MethodDescription
apply()It is used to invoke a function that takes this value as well as an array of arguments.
bind()It is used to implement a new function.
call()It is used to invoke a function that takes this value and a list of arguments.
toString()Returns the result in string.

You learned about JavaScript functions and how to build your very own functions in this tutorial. You may arrange your code with functions by separating everything into discrete blocks that execute various tasks.