Search code examples
javascriptglobal-variables

Javascript - change outside variable inside a function after passing it as an argument


I have a simple function and I want it to be executed only once. Therefore I created status.example_1 and status.example_2. When the function is executed status should change from false to true, but it doesn't work. It is passed to myFunction as an argument e2 and this is the cause of the problem.

Is there any way to make it work? What am I missing here?

(function(){
    
    var btn1 = document.getElementById('btn-1'),
        btn2 = document.getElementById('btn-2'),
        status = {
            example_1:  false,
            example_2:  false,
        };
      
    function myFunction(e1,e2){
        if(e2 === false){
            console.log('Button: ' + e1);
            e2 = true;
        }
    }
    
    btn1.addEventListener('click',function(){
        myFunction(1,status.example_1);
    });
    
    btn2.addEventListener('click',function(){
        myFunction(2,status.example_2);
    });
    
})();
<button id="btn-1">Click-1</button>
<button id="btn-2">Click-2</button>


Solution

  • your function should receive the entire object to be able to modify it, as you are passing only 1 property, it is like a new variable, instead:

    function myFunction(e1,e2){
        if(e2 === false){
            console.log('Button: ' + e1);
            e2 = true;
        }
    }
    

    you can try

    function myFunction(e1,status){
        if(status[`example_${e1}`] === false){
            console.log('Button: ' + e1);
            status[`example_${e1}`] = true;
        }
    }
    

    and

    myFunction(2,status);