Friday, 31 August 2018

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

No comments:

Post a Comment