JavaScript Tutorial JavaScript References

JavaScript Functions - Pass by Value



When the argument or parameter of a function is passed by value, then the function takes only the value of parameter and any changes made to the parameter inside the function have no effect on the parameter.

Example:

In the example below, a function called Square is created which returns square of the passed argument. The function modify the parameter as square of itself before returning it. In this program, the passed argument is printed before and after calling the function Square. The value of the passed parameter remains unaffected because it was passed by value.

function Square(x) {
  x = x * x;
  document.write("Value of x inside function: ",
                  x, "<br>");
}

var x = 5;

document.write("Value of x before passing to the function: ",
                x, "<br>");

//calling the function
Square(x);

document.write("Value of x after passing to the function: ",
                x, "<br>");

The output of the above code will be:

Value of x before passing to the function: 5
Value of x inside function: 25
Value of x after passing to the function: 5

❮ JavaScript - Functions

5