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

178
Views
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 answers
Answer question

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 Report
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!