'New property assignment to object leads to weird behaviour in NodeJS

On a recent interview process, I was asked to write code for an API. I used NodeJS, v16.14.0.

However, I encountered some very weird behavior:

module.exports = {
    findSomething: (data) => {

        const keys = Object.keys(data).sort();

        let maxObj = null;
        let maxKey = null;
        for (let i = 0; i < keys.length; ++i) {
            let key = keys[i];
            const currObj = data[key];
            if (maxObj == null || currObj.prop > maxObj.prop) {
                maxObj = currObj;
                maxKey = key;
            }
        }
        
        // Attempt to assign a new property to the object:

        // Variant 1, causes odd behaviour.
        maxObj.maxKey = maxKey;

        // Variant 2, object copy - works OK.
        let newData = {...maxObj}
        newData.maxKey = maxKey;
        return newData;
    }
}

This very minor change (Variant 1 instead of 2), gave no errors, however led the function behave very oddly. sometimes producing right results and others just nothing. This led me to lose precious time, and eventually I was stunned to find it out.

I am not aware of cases of such behaviour. As I want to learn from this and get better, are you aware of why this could possibly happen, or if I am missing something obvious here? I know that assigning a new property to an existing object is fine in JavaScript, and my variables were all within scope usage.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source