Thursday 30 August 2018

JavaScript: functions

Function is a block of statements used to reuse the code. Functions are defined using function keyword

How to define a function?
function functionName(argument1, argument2....argumentN){
         //Block of statements
}

How to call a function?
functionName(argument1, argument2....argumentN)

A function can take zero (or) more arguments.

Zero argument function
function helloWorld(){
         document.write("Hello World");
}

One argument function
function square(x){
         return x*x;
}
Above function takes a number and return the square of it.

Two-argument function
function sum(x, y){
         return x+y;
}

Above function calculates the sum of two numbers.

functions.html
<!DOCTYPE html>

<html>

<head>
    <title>Functions Example</title>
</head>

<body>
    <script type="text/javascript">
        function helloWorld() {
            document.write("Hello World");
        }

        function square(x) {
            return x * x;
        }

        function sum(x, y) {
            return x + y;
        }

        document.write("Square of 5 is " + square(5) + "<br />");
        document.write("Sum of 10 and 20 is " + sum(10, 20) + "<br />");
        helloWorld();
    </script>
</body>

</html>

Open above page in browser, you can able to see following lines.

Square of 5 is 25
Sum of 10 and 20 is 30
Hello World
                          
Method Vs function
If a function is assigned to the property of object is called method.

What is constructor?
Functions that are designed to initialize the object are called constructors.




Previous                                                 Next                                                 Home

No comments:

Post a Comment