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.

>Solution :

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
        }
    }
}

Leave a Reply