This tutorial explains how JavaScript pass by value works and gives you some examples of passing primitive and reference variables to a function.

JavaScript pass by value or pass by reference

In JavaScript, all function arguments are always passed by value. It means that JavaScript copies the values of the passing variables into arguments inside of the function.

Any changes that you make to the arguments inside the function does not affect the passing variables outside of the function. In other words, the changes made to the arguments are not reflected outside of the function.

If function arguments are passed by reference, the changes of variables that you pass into the function will be reflected outside the function. This is not possible in JavaScript.

Passing by value of primitives values

Let’s take a look at the following example.

function square(x) {
    x = x * x;
    return x;
}
var y = 10;
var result = square(y);
console.log(y); // 10 -- no change
console.log(result); // 100 

How the script works.

First, define a square() function that accepts an argument x . The function changes the value of the x argument.

#javascript #programming #developer #web-development

Understanding JavaScript Pass By Value
1.60 GEEK