2

I recently started learning functional programming in Javascript, and one thing that's valued is Immutability. One way to preserve immutability is to when we want to modify some object that we first create a copy and then modify that copy and return it, for example:

const person = {
    firstName: 'John',
    lastName: 'Smith',
}

const modifyFName = obj => {
    const objCopy = {...obj};
    objCopy.firstName = 'James';
    return objCopy;
}

console.log(modifyFName(person)) // {firstName: 'James', lastName: 'Smith'}
console.log(person) // {firstName: 'John', lastName: 'Smith'}

But if I want to modify some deeply nested object creating shallow copy like one above wouldn't make much of a difference, for example:

const person = {
    firstName: 'John',
    lastName: 'Smith',
    parents: {
        mom: {
            firstName: 'Jennifer',
            lastName: "Swift"
        },
        dad: {
            firstName: 'Tom',
            lastName: 'Cartman'
        }
    }
}

const modifyDadName = obj => {
    const objCopy = {...obj};
    objCopy.parents.dad.firstName = 'Aurelion';
    return objCopy;
}

console.log(modifyDadName(person)) // {... dad: "Aurelion"}
console.log(person) // {... dad: "Aurelion"}

Both objects have changed. So I am wondering in this situation should I perhaps use deep copy, or maybe use some third-party Immutable data structures, or is there some other solution for this?

1 Answer 1

5

You're right that a shallow copy doesn't help, but you don't need a full deep copy, you only have to make copies of the things you want to change. In your case, that's person, parents, and dad, but not mom:

const modifyDadName = obj => {
    return {                            // Replacement `obj` (`person`)
        ...obj,
        parents: {                      // Replacement `obj.parents`
            ...obj.parents,
            dad: {                      // Replacement `obj.parents.dad`
                ...obj.parents.dad,
                firstName: "Aurelion",  // New name
            }
        }
    };
};

dad changes because, well, that's the operation we're doing (changing firstName). :-) parents changes because changing dad means there's a new object on its dad property. person (obj) changes because there's a new parents object. But mom doesn't change, so we can reuse the same object.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.