Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
        }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading