Friday, 31 August 2018

JavaScript: Nested functions

You can define function inside other function. Embedded function can able to access all the variables defined in enclosing function.

embedded.html
<!DOCTYPE html>

<html>

<head>
    <title>Embedded Functions</title>
</head>

<body>
    <script type="text/javascript">
        //Calculate (b*b - 4*a*c)/2*a 
        function descriminator(a, b, c) {
            return (square(b) - 4 * a * c) / twice(a);

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

            function twice(x) {
                return 2 * x;
            }
        }

        document.write("Discriminator of 5, 10, 3 is : " + descriminator(5, 10, 3));
    </script>
</body>

</html>

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

Discriminator of 5, 10, 3 is : 4

Scope of variables
Embedded function can able to access all the variables defined in parent function and any other variable where parent function has access.


Previous                                                 Next                                                 Home

JavaScript: Function expressions

Functions are first class citizens in JavaScript, just like how you use variables (like passing them as arguments), you can also use functions.

Example
var sum = function(a, b){
         return (a+b);
}

Above statements define a function sum using function expression.

functionExp.html
<!DOCTYPE html>

<html>

<head>
    <title>Function Expressions</title>
</head>

<body>
    <script type="text/javascript">
        var sum = function(a, b) {
            return (a + b);
        }

        var sub = function(a, b) {
            return (a - b);
        }

        document.write("Sum of 10 and 20 is " + sum(10, 20) + "<br />");
        document.write("Subtraction of 10 and 20 is " + sub(10, 20) + "<br />");
    </script>
</body>

</html>

Load above page in browser, you can able to see following text.

Sum of 10 and 20 is 30
Subtraction of 10 and 20 is -10

In fact you can also provide a name to functional expression, especially it is useful in recursive calls.

var factorial = function fact(n){
         if(n < 2)
                  return 1;
         return n * fact(n-1);
}


functionExp1.html
<!DOCTYPE html>

<html>

<head>
    <title>Pass by value and reference</title>
</head>

<body>
    <script type="text/javascript">
        var factorial = function fact(n) {
            if (n < 2)
                return 1;
            return n * fact(n - 1);
        }

        document.write("Factorial of 5 is " + factorial(5) + "<br />");
        document.write("Factorial of 10 is " + factorial(10) + "<br />");
    </script>
</body>

</html>

Load above page in browser, you can able to see following text.

Factorial of 5 is 120
Factorial of 10 is 3628800

Where can I use function expressions?
There are two primary advantages.
a. You can call a function as an argument to other function.
var square = function(x){
         return x*x;
}
                          
var cube = function(x){
         return x*x*x;
}
                          
var process = function(fun, x){
         return fun(x);
}

process(square, 5): Calculates square(5).
process(cube, 10): Calculates cube(10).


fun1.html
<!DOCTYPE html>

<html>

<head>
    <title>Functional Expression</title>
</head>

<body>
    <script type="text/javascript">
        var square = function(x) {
            return x * x;
        }

        var cube = function(x) {
            return x * x * x;
        }

        var process = function(fun, x) {
            return fun(x);
        }

        document.write("Square of 5 is " + process(square, 5) + "<br />");
        document.write("Cube of 10 is " + process(cube, 10) + "<br />");
    </script>
</body>

</html>

Load above page in browser, you can able to see following text.

Square of 5 is 25
Cube of 10 is 1000

b. You can able define functions based on a condition
var myFun;
                          
function defineFunction(num){
         if(num == 1){
                  myFun = function(x){
                           return x*x;
                  }
         }
         else{
                  myFun = function(x){
                           return x*x*x;
                  }
         }
}
                          

fun2.html
<!DOCTYPE html>

<html>

<head>
    <title>Functional Expression</title>
</head>

<body>
    <script type="text/javascript">
        var myFun;

        function defineFunction(num) {
            if (num == 1) {
                myFun = function(x) {
                    return x * x;
                }
            } else {
                myFun = function(x) {
                    return x * x * x;
                }
            }
        }

        defineFunction(1); // Define square functionality
        document.write("Square of 5 is " + myFun(5) + "<br />");

        defineFunction(2); // Define cube functionality
        document.write("Cube of 10 is " + myFun(10) + "<br />");
    </script>
</body>

</html>

Load above page in browser, you can able to see following text.
Square of 5 is 25
Cube of 10 is 1000




Previous                                                 Next                                                 Home

JavaScript: Pass by value and Pass by reference

If you pass primitive values as an argument to a function, it works as pass by value, means if the function changes the argument values, these changes are not visible outside.

If you pass object (or) arrays as an argument to function, it works as pass by reference and the changes happens to the arguments inside the function are visible outside the function.

functionCall.html
<!DOCTYPE html>

<html>

<head>
    <title>Pass by value and reference</title>
</head>

<body>
    <script type="text/javascript">
        function square(x) {
            x = x * x;
            return x;
        }

        function changeObj(person) {
            person.firstName = "Phalgun";
        }

        var x = 10
        var person1 = {
            firstName: "Hari Krishna",
            lastName: "Gurram"
        }

        document.write("Before calling functions <br />");
        document.write("x = " + x + "<br />");
        document.write("person1.firstName = " + person1.firstName + "<br />");
        document.write("person1.lastName = " + person1.lastName + "<br />");

        square(10);
        changeObj(person1);

        document.write("<br /> After calling functions <br />");
        document.write("x = " + x + "<br />");
        document.write("person1.firstName = " + person1.firstName + "<br />");
        document.write("person1.lastName = " + person1.lastName + "<br />");
    </script>
</body>

</html>

Load above page in browser, you can able to see following output.

Before calling functions
x = 10
person1.firstName = Hari Krishna
person1.lastName = Gurram

After calling functions
x = 10
person1.firstName = Phalgun
person1.lastName = Gurram

As you see updated value of the variable x is not reflected outside the function, where as updated value of the person firstName is reflected outside.


Previous                                                 Next                                                 Home

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

JavaScript: null Vs undefined

Both null and undefined are used to represent a variable with no value. But there is a small difference between these two.

undefined
If you declare a variable without assigning any value, then it is treated as undefined.

null
You can assign null to any variable to specify that variable has no value, but you can’t assign undefined to any variable.

One more difference is type of null return object, where as type of undefined return undefined.

Comparison of null and undefined
 null === undefined // Strict comparison operator return false
 null == undefined // true
 null == null // true
undefined == undefined //true

undefined.html
<!DOCTYPE html>

<html>

<head>
    <title>null Vs undefined</title>
</head>

<body>
    <script>
        var a;
        var b = null;

        document.write("a = " + a + " Type of a = " + (typeof a) + "<br />");
        document.write("b = " + b + " Type of b = " + (typeof b) + "<br />");
        document.write("a == b : " + (a == b) + "<br />");
        document.write("a === b : " + (a === b) + "<br />");
        document.write("a == a : " + (a == a) + "<br />");
        document.write("b == b : " + (b == b) + "<br />");
    </script>
</body>

</html>

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

a = undefined Type of a = undefined
b = null Type of b = object
a == b : true
a === b : false
a == a : true
b == b : true


Previous                                                 Next                                                 Home

JavaScript: Iterating over all properties of object

for..in loop is used to iterate over all the properties of object.

Syntax
for(property in object){
         var val = object[property];
}

iterate.html
<!DOCTYPE html>

<html>

<head>
    <title>iterate Object</title>
</head>

<body>
    <script type="text/javascript">
        var person1 = {
            firstName: "Hari Krishna",
            lastName: "Gurram",
            city: "Bangalore",
            area: "Marthalli"
        };

        for (property in person1) {
            document.write(property + " : " + person1[property] + "<br />");
        }
    </script>
</body>

</html>


Previous                                                 Next                                                 Home

JavaScript: instanceof : Check the class

‘instanceof’ operator is used to tests whether an object has in its prototype chain the prototype property of a constructor.

Syntax
object instanceof constructor

instanceof.html
<!DOCTYPE html>

<html>

<head>
    <title>instanceof operator Example</title>
</head>

<body>
    <script>
        function A() {

        }

        function B() {

        }

        function C() {

        }

        // Apply prototype inheritance
        C.prototype = new B();

        var obj = new C(); // obj is instance for both B and C

        document.write("(obj instanceof A) : " + (obj instanceof A) + "<br />");
        document.write("(obj instanceof B) : " + (obj instanceof B) + "<br />");
        document.write("(obj instanceof C) : " + (obj instanceof C) + "<br />");
    </script>
</body>

</html>

Load above page in browser, you can able to see following text.

(obj instanceof A) : false
(obj instanceof B) : true
(obj instanceof C) : true



Previous                                                 Next                                                 Home

JavaScript: hasOwnProperty(): Check whether object has given property (or) not

In previous post, I explained how to test for the property of an object using 'in' operator. JavaScript also provides
hasOwnProperty() method to test, whether an object owns given property (or) not.

Syntax
object.hasOwnProperty(propertyName)

Above method return true, if the object has given property, else false.

properties.html
<!DOCTYPE html>

<html>

<head>
    <title>objects</title>
</head>

<body>
    <script type="text/javascript">
        var employee = {
            firstName: "Hari Krishna",
            age: 26
        };

        document.write("employee.hasOwnProperty(\"firstName\") : " + employee.hasOwnProperty("firstName") + "<br />");
        document.write("employee.hasOwnProperty(\"age\") : " + employee.hasOwnProperty("age") + "<br />");
        document.write("employee.hasOwnProperty(\"lastName\") : " + employee.hasOwnProperty("lastName") + "<br />");
    </script>
</body>

</html>

Load above page in browser, you can able to see following text.

employee.hasOwnProperty("firstName") : true
employee.hasOwnProperty("age") : true
employee.hasOwnProperty("lastName") : false


Previous                                                 Next                                                 Home

JavaScript: in: Check for property existence in object

'in' operator is used to check for the existence of a property in an object.

Syntax
property in object

Above statement return true if object has given property, else false.

in.html

<!DOCTYPE html>

<html>

<head>
    <title>in operator</title>
</head>

<body>
    <script type="text/javascript">
        var person1 = {
            firstName: "Hari Krishna",
            lastName: "Gurram",
            address: {
                city: "Bangalore",
                area: "Marthalli"
            }
        };

        // Print "person1 has property firstName"
        if ("firstName" in person1) {
            document.write("person1 has property firstName <br />");
        } else {
            document.write("person1 don't have property firstName <br />");
        }

        // Print "person1 don't have property country"
        if ("country" in person1) {
            document.write("person1 has property country <br />");
        } else {
            document.write("person1 don't have property country <br />");
        }
    </script>
</body>

</html>



Previous                                                 Next                                                 Home

JavaScript: Nested objects

An object can be nested inside other object.

var person1 = {
         firstName: "Hari Krishna",
         lastName: "Gurram",
         address:{
                  city: "Bangalore",
                  area: "Marthalli"
         }
};

As you see above snippet, address object is embedded inside person1 object.

nested.html
<!DOCTYPE html>

<html>

<head>
    <title>Nested Object</title>
</head>

<body>
    <script type="text/javascript">
        var person1 = {
            firstName: "Hari Krishna",
            lastName: "Gurram",
            address: {
                city: "Bangalore",
                area: "Marthalli"
            }
        };

        document.write("firstName : " + person1.firstName + "<br />");
        document.write("lastName : " + person1.lastName + "<br />");
        document.write("city : " + person1.address.city + "<br />");
        document.write("area : " + person1.address.area + "<br />");
    </script>
</body>

</html>



Previous                                                 Next                                                 Home

JavaScript: . Vs []: accessing properties

As I said, there are two ways to access properties associated with an object.

Syntax
var a = object.property; // Access the value associated with given property using '.' notation.

var a = object["property"]; // Access the value associated with given property using [].

If a property has space (or) start with a number, you can only access using [] notation.

Ex:
person1["first name"] = "Hari Krishna";
person1["last name"] = "Gurram";

objIndex.html
<!DOCTYPE html>

<html>

<head>
    <title>Index Notation</title>
</head>

<body>
    <script type="text/javascript">
        var person1 = new Object();

        person1["first name"] = "Hari Krishna";
        person1["last name"] = "Gurram";

        document.write("person1['first name'] : " + person1["first name"] + "<br />");
        document.write("person1['last name'] : " + person1["last name"] + "<br />");
    </script>
</body>

</html>

Suppose your application reads a property name and gives you the value associated with that property, you need to use [] notation.

properties.html
<!DOCTYPE html>

<html>

<head>
    <title>objects</title>
</head>

<body>
    <script type="text/javascript">
        var capitals = {
            india: "New Delhi",
            sweden: "Stockholm",
            japan: "tokyo"
        }

        var str = prompt("Enter country name")
        alert("Capital of " + str + " is " + capitals[str]);
    </script>
</body>

</html>

Load above page in browser, it prompts for country name and return the capital of the country.

One more thing is you can iterate through all the properties and values associated with the property only by using [] notation.


Object.html
<!DOCTYPE html>

<html>

<head>
    <title>objects</title>
</head>

<body>
    <script type="text/javascript">
        function Employee(firstName, lastName, id) {
            this.firstName = firstName;
            this.lastName = lastName;
            this.id = id;
        }

        function printEmployee(employee) {
            for (property in employee) {
                document.write(property + " : " + employee[property] + "<br />");
            }
            document.write("<br />");
        }

        /* Create an object of type Employee */
        var emp1 = new Employee("Hari Krishna", "Gurram", 123);
        var emp2 = new Employee("Sankalp", "Dubey", 987);

        printEmployee(emp1);
        printEmployee(emp2);
    </script>
</body>

</html>




Previous                                                 Next                                                 Home

JavaScript: Objects

An object is an entity that is uniquely identified among other objects. In JavaScript, object is modeled as unordered collection of properties, each property has a name and value associated with it.

var obj = {property1: value1, property2: value2, ....propertyN: valueN};

In the following post, I explained about an object in general.

How to define object?
Following three ways are used to define an object.

var obj = new Object(); // Define empty object
var obj = {}; // Define empty object
var obj = {property1: value1, property2: value2, ....propertyN: valueN}; // Define object with properties.

How to add properties to an object?
You can add properties to an object using . notation (or) by using [].

Syntax
object.property = value;
object["property"] = value;

How to access the value associated with an object?
It is same like adding properties to an object. You can access the value associated with an object using . (or) [] notation.

Syntax
var a = object.property; // Access the value associated with given property.

var a = object["property"]; // Access the value associated with given property.

object.html
<!DOCTYPE html>

<html>

<head>
    <title>Objects example</title>
</head>

<body>
    <script type="text/javascript">
        var person1 = new Object();
        var person2 = {};
        var person3 = {
            firstName: "Hari Krishna",
            lastName: "Gurram",
            age: 27
        }

        // Adding properties to person1
        person1.firstName = "Senthil";
        person1.organization = "Symantec";

        // Adding properties to person2
        person2["firstName"] = "Sandesh";
        person2["id"] = 54321;

        /* Accessing using . notation */
        document.write("person1 details <br />");
        document.write("******************************************<br/>");
        document.write("firstName : " + person1.firstName + "<br />");
        document.write("lastName : " + person1.lastName + "<br />");
        document.write("age : " + person1.age + "<br />");
        document.write("organization : " + person1.organization + "<br />");
        document.write("id : " + person1.id + "<br />");

        /* Accessing using [] */
        document.write("<br />person2 details <br />");
        document.write("******************************************<br/>");
        document.write("firstName : " + person2["firstName"] + "<br />");
        document.write("lastName : " + person2["lastName"] + "<br />");
        document.write("age : " + person2["age"] + "<br />");
        document.write("organization : " + person2["organization"] + "<br />");
        document.write("id : " + person2["id"] + "<br />");

        /* Accessing using . notation */
        document.write("<br />person3 details <br />");
        document.write("******************************************<br/>");
        document.write("firstName : " + person3.firstName + "<br />");
        document.write("lastName : " + person3.lastName + "<br />");
        document.write("age : " + person3.age + "<br />");
        document.write("organization : " + person3.organization + "<br />");
        document.write("id : " + person3.id + "<br />");
    </script>
</body>

</html>

Objects in JavaScript are dynamic, you can add properties to an object any time and delete properties any time.



Previous                                                 Next                                                 Home