Search code examples
javascriptfunctiononclickpush

No access to the array pushed in the function; Outside the function with Onclick in JavaScript


I defined an array outside the function, then defined a function and inside the function pushed values into the array.

The problem is that if I call the function with Onclick. I don't have access outside the function to the values I pushed inside the function:

<body>
    <input type="button" value="click me" onclick="you()">

    <script>
        var me = [4];

        function you() {
            me.push(2, 3);
            console.log('inside = ' + me)

            //Displayed value in console after click: inside = 4,2,3

        }
        console.log('outside = ' + me);

        //Displayed value in console after and before click: outside = 4

    </script>
</body>

But if I call the same function inside JavaScript; In that case, outside of the function as well, I will have access to the values pushed into the function:

<body>

    <script>
        var me = [4];

        function you() {
            me.push(2, 3);
            console.log('inside = ' + me)

            //Displayed value in console: inside = 4,2,3

        }

        you();
        console.log('outside = ' + me);

        //Displayed value in console: outside = 4,2,3

    </script>
</body>

How can I access outside the function the values that I pushed inside the function by Onclick?

I tried the same method as above, but I did not find an answer even by searching; I would be very happy if you could help me.


Solution

  • In your first example, your console.log is ran BEFORE the you() function is called. So it can't show the updates as they haven't happened yet.

    You will need to run a function later on to see the newest updates.

    In the below test example, if you first click the click me button, the array is updated. Then clicking the second button you will see the updated array.

    var me = [4];
    
    function you() {
      me.push(2, 3);
      console.log('inside = ' + me)
    }
    
    function seeUpdates(){
      console.log('outside = ' + me);
    }
    <input type="button" value="click me" onclick="you()">
    <input type="button" value="See Updates" onclick="seeUpdates()">