Search code examples
javascriptarrayspass-by-referencejavascript-objectspass-by-value

Storing references to values, in arrays, then reassigning the original variable (JavaScript)


This is what I want to do:

I have an object that stores a state and also an array of the previous states.

var object = { currentState: [Object], previousStates: [[Object], [Object]] };

When the state changes I want to store the reference to currrentState's object in the previous states array so that it can be reused, then create a new state (or reuse an old state) and store it in currentState WITHOUT changing the original object passed to the array. If it makes any difference at all, the states are instantiated class objects.

Is this possible?

I have looked at lots of resources on passing by reference and passing by value but I think I need it explained in the context of an example. Which example will store a new state at currentState without changing the previous value pushed to the array if either?

function changeState1(states) {
    states.previousStates.push(states.currentState);
    states.currentState = new State();
}

function changeState2(states) {
    var newState = new State();
    states.previousStates.push(states.currentState);
    states.currentState = newState;
}

EDIT:

I should probably mention that my intention is to create efficient code. I don't want to recreate states from classes on the fly if I can reuse old instances. It's better for memory usage and reduces garbage collection.


Solution

  • Maybe something like this?

    var obj = newObjectState; object.previousStates.push(object.currentState); object.currentState = obj;

    Of course this is all a kind of pseudocode but could be the answer you are looking for?