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

183
Visualizações
if can't access parameter in JavaScript module

Hi I'm having problems with the scope of an if in a JavaScript module. Here is a mock up of my code :

module.exports = {
caser(nb){
if(0 === 0){
nb = 3+2
}
}
}

The function is called from another JavaScript file. Nb however doesn't change when I do this. My editor (visual studio code) marked nb as unused. This I tried :

module.exports = {
caser(nb){
let number = nb
if(0 === 0){
number = 3+2
}
}
}

This still doesn't seem to alter the value of nb. Does anyone know a solution to this problem? Thanks in advance.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Reassigning nb (or number) will only change what those variable names point to in the current function. It sounds like what you need to do is return the changed value, and have the consumer of the function use it to reassign the value it passes in. Something like:

// consumer file:
const { caser } = require('./foo');

let nb = 5;
nb = caser(nb);
module.exports = {
    caser(nb) {
        if (0 === 0) {
            nb = 3 + 2
        }
        return nb;
    }
}

The only way to avoid having to reassign in the consumer would be for the consumer to pass an object instead, and mutate the object.

// consumer file:
const { caser } = require('./foo');

const objToPass = { nb: 5 };
caser(objToPass);
module.exports = {
    caser(objToPass) {
        if (0 === 0) {
            objToPass.nb = 3 + 2
        }
    }
}
about 4 years ago · Juan Pablo Isaza Relatório
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