Skip to content
Advertisement

Copy value of local variable to a global variable in JavaScript

I am trying to update the value of a global variable based on the local variable which is defined inside a function.

I read here on Stack Overflow to use the window object, but still it’s not working.

JavaScript
JavaScript

Here is the JSFiddle – https://jsfiddle.net/t18ofd65/8/

Advertisement

Answer

You are fundamentally misunderstanding what attaching a click event is doing. This code does not run sequentially line by line

JavaScript

Line 1 executes, followed by line 2. But line 3 does not execute until the button is actually clicked. Line 5 executes immediately after line 2.

If you added a console.log(z) or indeed a console.log(window.z) inside the event handler (ie, after line 3) you would see it actually updates the variable.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement