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.
UPDATE : this as been resolved by @Telman
It has been resolved by adding "profil1 =" to :
CALL THE FUNCTION profil1 = carte_adherent.profil(adherent_type,profil1);
carte_adherentprofil,profil1is a parameter, which is just a local variable initialised from the calling argument. It is shadowing the outer variableprofil1. Assigning to the innerprofil1insideprofilthus has no impact on the outerprofil1. Ifprofil1is not a parameter, there will be no shadowing, andprofil1insideprofilwill refer to the outer scopeprofil1, resulting inprofil1 == "Particulier".let x = 3; function a(x) { x = 7; }; a(x); console.log(x)(producing3, not7, because of shadowing). OP's function will never result in anything other thanundefinedinprofil1, regardless of if the function is called, or what the value ofadherent_typeis.profil1will always beundefinedin this case. I was stating that the functionprofilis returning the expected value. But I guess OP is stating that they are evaluatingprofil1after the function has completed, not evaluating the result of theprofilfunction.