Search code examples
javascriptnode.jspass-by-reference

Node.js how to pass function argument by reference in practice


I have found the following suggestions on how to pass parameter by reference using built-in JavaScript functionality:
[Javascript] Pass By Value And Pass By Reference In JavaScript
TypeScript pass by ref parameter [duplicate]

However, none of them work in practice. Consider the following code example:

let data = {
    prop1: '[1,2,3]',
    prop2: '{"abc":"def"}'
}

function parseString(ref prop) {
    if(typeof prop === 'string') {
        prop = JSON.parse(prop);
    }
}

parseString(data.prop1);
parseString(data.prop2);

Using the boxing approach {item: data.prop1} does not work because the box will contain a copy and not a reference to the original data.prop1 property.

How to properly implement the above example?


Solution

  • One way to implement parseString function is by specifying the parent object and a string to indicate the referenced property. Here is the code that implements the example:

    function parseString(data, propName) {
        if (!Object.keys(data).includes(propName)) {
            throw new Error(`Object does not contain key ${propName}.`);
        }
    
        if(typeof prop === 'string') {
            data[propName] = JSON.parse(data[propName]);
        }
    }
    
    parseString(data, 'prop1');
    parseString(data, 'prop2');