javascriptpass-by-reference

How to pass variable by reference?


in the other programming languages we use & keyword for passing variable by reference.

for example, in php;

$a = 10;

function something(&$a){
    $a = 7;
};

something($a);

echo $a;
// 7

How can we do this in javascript ?

When user click the right or left arrow, I'm trying to get next or prev. image by array index;

list: function (index) {
    let items = this.images;
    return {
        next: function () {
            if (index > items.length -1) {
                index = 0;
            }
            return items[index++];
        },
        prev: function () {
            if (index < 0) {
                index = items.length -1;
            }
            return items[index--];
        }
    }
}

Outside of this iterator, I need to use index variable. But I only get old value... I want to get current index.


Solution

  • JavaScript is always pass-by-value, there's no concept of pass-by-reference in JavaScript*.

    You can mimic the effect by using a primitive version of an atom:

    let indexAtom = {value: 0};
    
    function changeIndex(atom) {
      atom.value = 5;
    }
    
    changeIndex(indexAtom);
    
    assert(indexAtom.value === 5);
    

    I will say that if you need this, you usually have a code smell, and need to rethink your approach.

    In your case, you should use a closure to achieve the same effect:

    list: function (startingIndex = 0) {
        let items = this.images;
        let index = startingIndex; // note that index is defined here, inside of the function
        return {
            next: function () {
                // index taken from closure.
                if (index > items.length -1) {
                    index = 0;
                }
                return items[index++];
            },
            prev: function () {
                // same index as the next() function
                if (index < 0) {
                    index = items.length -1;
                }
                return items[index--];
            }
        }
    }
    

    * A common misconception is that objects are pass-by-reference, it's confusing because an object's "value" is also referred to as its "reference", programmers and naming things. Objects are pass-by-value as well, but the value of an object is a special "thing" called its "reference" or its "identity". This allows multiple variables to hold the same "reference" to the same object.