Understanding Pass-by-value in PHP and JavaScript

If you read my article on comparing PHP and JavaScript arrow functions, there is one relevant discussion that I did not touch in that article, as it is an important concept to grasp.

In programming, when we pass a variable into a function, the function can either modify the original variable or create a copy of it to work with. This leads to two main strategies: pass-by-reference and pass-by-value.

Pass-by-reference means that when we pass a variable into a function, the function works directly with the original variable. Any changes made to the variable inside the function affect the original variable.

On the other hand, Pass-by-value means that when we pass a variable into a function, the function makes a copy of the variable and works with the copy. Any changes made to the variable inside the function only affect the copy, not the original variable.

PHP and JavaScript use pass-by-value for primitive data types (like numbers, strings, booleans), meaning that the original variable isn’t changed by the function. Let’s illustrate this in PHP:

$a = 14;
$incr = fn($a) => $a++;
$incr($a);
echo $a; // Outputs: 14

In this code, $a is passed by value into the arrow function $incr. The function $incr increments the value of $a, but this only affects the copy of $a inside the function, not the original variable $a. Hence, after calling $incr($a), the value of $a remains 14.

The equivalent JavaScript code also exhibits this pass-by-value behavior:

let a = 14;
let incr = (a) => a++;
incr(a);
console.log(a); // Outputs: 14

In this JavaScript code, a is passed by value into the arrow function incr. The function incr increments the value of a, but this only affects the copy of a inside the function, not the original variable a. Hence, after calling incr(a), the value of a remains 14.

Understanding how languages handle the passing of variables (either by reference or by value) is crucial in controlling the behavior of your functions and avoiding unintended side effects. In the case of PHP and JavaScript arrow functions dealing with primitive types, remember they use pass-by-value: they won’t modify the original variable.