Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

181
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda