Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

150
Views
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.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!