Home > Blockchain >  JavaScript Get variable content from a function
JavaScript Get variable content from a function

Time:08-02

I'm trying to understand JS, doing it with documentation.

Variable inside/outside a function is quite difficult.

I would like to do a module to execute a code written in multiple areas of my code to finally write it only once :)

// GLOBAL VARIABLES
let adherent_type, profil1;

//SOMEWHERE I ASSIGN A VALUE IN ADHERENT_TYPE VARIABLE
adherent_type = "famille";

//THE FUNCTION IN THE MODULE I CREATED IN NODEJS
function profil(adherent_type,profil1) {

    if (adherent_type === "famille") {
        profil1 = "Particulier";
    }

    return profil1;
}

// CALL THE FUNCTION 
carte_adherent.profil(adherent_type,profil1);

The result: profil1 = undefined

Variable adherent_type is ok, my issue is on profil1.

It is not working when I don't put "profil1" in the () of the function too.

Thank you very much for your help.

CodePudding user response:

you don't call a function this way in javascript

  carte_adherent.profil(adherent_type,profil1);

instead this

  profil(adherent_type,profil1);

now to see your result console it to the machine like this

  console.log(profil(adherent_type,profil1));

now try it an see the result but first make the changes above

CodePudding user response:

When you pass a variable to the function, the function creates a copy of it. So when you change the profil1 inside the function the value of the let profil1 is not changed (only the copy is changed).

What you can do is to return the value of profil from the function, and then assign the result to the profil1 variable.

function profil(adherent_type) {
    let newProfil;

    if (adherent_type === "famille") {
        newProfil = "Particulier";
    }

    return newProfil;
}

// CALL THE FUNCTION 
profil1 = carte_adherent.profil(adherent_type);

The option with globalThis probably also will work, in a case you want to make the profil1 variable global:

   function profil(adherent_type) {
        if (adherent_type === "famille") {
            globalThis.profil1 = "Particulier";
        }
    }
    
    // CALL THE FUNCTION 
    carte_adherent.profil(adherent_type);
    console.log(globalThis.profil1);

CodePudding user response:

yes that why you can't call the function that way are you using a class or a prototype

  • Related