JavaScript – Call By Value and Call By Reference

Call By Value:

  • Passing primitive value as input.
  • Value will be copied into parameter.
<html>
            <body>
                        <p id=”demo”></p>
                                    <script>
                                                function modify(y)
                                                {
                                                            y=y+10;
                                                            document.write(“y inside function : ” + y);
                                                }
                                                var x = 10 ;
                                                modify(x);
                                                document.getElementById(“demo”).innerHTML = x;
                                    </script>
            </body>
</html>

Call By Reference:

  • Passing object as an argument to a function.
  • Only object address will be stored into parameter.
<html>
            <body>
                        <p id=”demo”></p>
                                    <script>
                                                function modify(x)
                                                {
                                                            x[0]=x[0]+10;
                                                            document.write(“x[0] inside function : ” + x[0]);
                                                }
                                                var arr = [10, 20, 30, 40, 50] ;
                                                modify(arr);
                                                document.getElementById(“demo”).innerHTML = arr[0];
                                    </script>
            </body>
</html>
Scroll to Top