Skip to content

Avoid Side Effects (part 2) - Uses confusing pass-by-reference terminology #321

Description

@jdsandifer

Pass by reference is an older concept that doesn't truly exist in most modern programming languages. Because of this, it's meaning has become confused and twisted. It's also generally discouraged where it does exist. I recommend using different terms to avoid this confusion.

To understand true pass by reference, please look at this example code from the PHP docs here: https://www.php.net/manual/en/language.references.pass.php.

<?php
function foo(&$var)
{
    $var++;
}

$a=5;
foo($a);
// $a is 6 here
?>

Note how the how the original variable $a has it's value reassigned to be 6 because $var becomes an alias to that variable - it's like they're the same variable.

This is not possible in JavaScript.

Even with objects and arrays in JavaScript, you can't assign a new object to a variable outside a function by assigning the new object to a parameter of that function. (You can only change the original object using the parameter.)

Because of this, I recommend using the concept of Mutability to convey the information about how objects and arrays can be changed when passed to a function. Null, undefined, booleans, numbers, and strings are all immutable values and we don't need to worry about a function changing them. Objects and arrays are mutable values and thus we need to take care that we don't unintentionally change their contents/properties inside a function.

I want to credit Dan Abramov and his Just JavaScript course with introducing me to this idea. I've used JS for years and have only recently solidified my understanding of pass by value and this newer way of thinking about it recently thanks to him.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions