Functions in JavaScript

Functions in JavaScript

Functions in JavaScript play a very important role. Function is a group of codes designed for a specific task and is designed to avoid repetition of a code. We can also call function as a mini program to do any particular task. We need to call a function to execute it.

Functions are the great source to manage three things:

  1. Organization of the code
  2. Execution of the code
  3. Re-usability of the code

One by one I will explain each of them here for you please read patiently.

Lets begin with some basics of functions in JavaScript.

Example:

<script>
    function myFunction()
    {
    alert(‘Hello Friend’); //Defining a function what to do.
    }
myFunction(); //Here you are executing the function. Unless u call a function after defining it wont work.
</script>

Why is function used?

Function is used to avoid repetitions of codes. It is used so that we can assign different parameters to a function and get different results as well.

Example:

<!DOCTYPE html>
<html>
<body>
    <script>    
        var a = 20;
        var b = 30;
        var c = a + b;
        alert(c);         //result will be 50
        var a = 10;
        var b = 15;
        var c = a + b;
        alert(c);           //result will be 25
    </script>
</body>
</html>

In the above eg. A and b have different values each time but the calculation we want is same for all. So if we have a data of 20 pair of a and b values we have to repeat the whole thing 20 times as above. However this can be shortened by a single function for all 20 or more pairs of which we want the same logic to be applied. So the same can be written with a help of a function as below :

Example:

<script>
    function myFunction(a, b){
     return a + b;
    };
    alert (myFunction(2, 3)); // 5
    alert (myFunction(5, 10)); //15
    alert (myFunction(10, 20)); //30
//Here a same function is used to get different results with same logic to be applied and we do not need to repeat the code but just need to write it once.
</script>

How to write a function?

To write a function we have to define it with a keyword function followed by function name then (… parameters here if any …) followed by code written in { …code here… }

Example:

function myFunction(param1, param2)
    {
    Code to be written here …
    }
  • The name of a function should follow the same rules as of defining a variable. Best practice is to write all in small letters or camel case.
  • A ; (terminator) must be used to end each set of line of code.
  • If we need to bind any function with any event we need to define a function to trigger that function. It cannot be bind with just function name as the function will not be executed.

Example:

myfunction Or myFunction

Function myfunction(){
    Document.write(Hey Guyz !);  //a ; is used to end a line of code here
}

Eg.

<!DOCTYPE html>
<html>
<body>
<form>
    <input type="button" value="Click Me" id="press"></input>
</form>
<script>
    function myFunction(){
        alert('Hello!');
    }
    document.getElementById('press').onclick =  function(){        
        //Here you cannot directly bind a function with an event like document.getElementById(‘press’).onclick = myFunction(); because if we do it then the function will be executed automatically before the click.
        myFunction();
    }
</script>
</body>
</html>

function with Parameters

Suppose if we need any extra information with your function we use parameters. If we need a function to wish any user but we are not sure what the users name is or we are expecting any random name of a user we can do it by using parameter with a function declaring code to wish the user.

Example:

Single Parameter

<script>
        function autoWish(name){
            alert("Hello " + name);
        }
        autoWish('Raj');    //Hello Raj
        autoWish('Tina');//Hello Tina
        autoWish('Rohit');//Hello Rohit
        autoWish('Amit');//Hello Amit
</script>

Example:

Multiple Parameter (You can use as many parameters you want in a function as per your need.

<script>    
        function autoStatement(name, sex, age){
            alert(name + ' is a ' + sex + ' who is ' + age + ' years old.');
        }
        autoStatement('Raj', 'Male', '25');    //Raj is a Male who is 25 years old.
        autoStatement('Tina', 'Female', '34');    //Tina is a Female who is 34 years old.
        autoStatement('John', 'Male', '51');    //John is a Male who is 51 years old.
        autoStatement('Ravi', 'Male', '29');    //Ravi is a Male who is 29 years old.
 </script>

return in a function:

Sometimes we use function to get a popup or to print something on the screen. But sometimes we need a function to get a value or to calculate and get the sum or product in return.

But to get a return value make sure you print it or you won’t be able to see it on screen.

Example:

<script>        
        function addNumbers(a, b){
            var c = a + b;
            return c;
            }
            addNumbers(2, 3 );     //Its not going to show any thing on screen as its just a value and not yet printed.    
            document.write(addNumbers(2, 3));    //5
<script>

Calling function from another function

We can always call a function from another function or can use any function as a variable as well.

Example:

<script>    
        function firstFunct(){
            document.write(“This is my first Function. ”);
        }    
        function secondFunct(){
            document.write(“And this is my second one  ”);
        }
       function trigger(){
         firstFunct();
         secondFunct();
       }
       trigger();    //This is my first Function. And this is my second one
</script>

Global & Local Variables in a Function / Scope of a Function Local or Global

Scope is basically the reach of a Function or a variable. Concept of Local & Global is quiet simple as any variable outside a function is a Global variable and it can be used by any other functions. However a

Local variable is a variable inside any particular function and hence it can only be used by that particular function only or its child or sibling functions.

Example 1:

<script>
        var a = 5;    //This variable is a Global Variable
        function add(){
            var b = 10;    //This variable is a Local Variable
            alert(a + b);
        }
        add(); // 15
</script>

Above function can access both of the variables as one is in local scope declared inside it and other one is global declared outside of function.

Scope in nested function

Example 2:

<script>    
        var a = 5;    //This variable is a Global Variable
        function add(x, y){
            var b = 10;    //This variable is a Local Variable
            function nestedFunc(m, n){
                alert(a + b + m + n + x + y);
            }
            nestedFunc(2,5);
        }
        add(4,4); // 30
 </script>

See how we can access all the arguments, global variables, local variables from the child function of add function. It is known as the lexical scope in JavaScript.

Although in general parameters are very akin to local variables yet there are some differences and those need to clarified properly here. The biggest and very clear difference is that you can pass the values to the function parameters or arguments while calling it but local variables have their fixed values and can not be changed at the time of call.

Example:

function myFunc(name, age){
    alert(Hello+” ”+name+”! You are ”+age+”yrs old.”);
}
//lets call the function
myFunc('Ravi', 35); //Hello Ravi! You are 35yrs old.
myFunc('Sonia', '32'); //Hello Sonia! You are 32yrs old.

You can see how I passed the values to the given arguments to get the variety of results.

Functions as Closures in JavaScript

See the example:

var person = function (){
    var age = 55;
    var name = 'Ravi';
    alert(“Age of ”+name +” is ”+age+”yrs old.”);
}
//calling the closure
person();//will get an alert with the expected message.

Functions as Object in JavaScript

Functions are the base for Object Oriented JavaScript as JavaScript doesn’t offer good support for class construct for all the browsers so function is only a way to create objects. In future class construct will be a good option to deal with objects like other programmings.

JavaScript is not classical inheritance based language it supports prototypical inheritance so far.

Lets create an ‘InstituteInfo’ object in JavaScript:

function InstituteInfo(){
    //declaring properties
    this.name = 'ADMEC Multimedia Institute';
    this.specialization = 'multimedia, programmings, and cad courses';
    //declaring methods
    this.teachingMethodology = function (){
        return this.name+” offers training in ”+this.specialization;
    }
}
//instantiating our object
var getInstituteInfo = new InstituteInfo();
alert(getInstituteInfo.name);
alert(getInstituteInfo.specialization);
alert(getInstituteInfo.teachingMethodology);

Summary:

Functions are the backbone of JavaScript which provide a solid ground to JavaScript developers. From procedural code to advanced OOJS or Object Oriented JavaScript, functions are building stones.

Although there are hundreds of uses of JavaScript functions but I included the most common and basic ones to increase your understanding of functions in JavaScript. For more JavaScript tutorials please keep visiting here or attend our classes from the experts at our training center in Delhi, India.

This article is an assignment issued by Ravi Sir to one of our JavaScript students i.e. Tariq. He is a great JavaScript enthusiastic and he loves to explore such things in JavaScript always.

Leave a Reply

You must be logged in to post a comment.

Copy link