Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

143
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda