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.

<input type="text" id="getCity" placeholder="Enter"></input>
<button id="btn" type="Submit">Submit</button>
var z = 0;
$('#btn').click(function() {
  window.z = 1
});
console.log(z)

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

var z = 0;                   // Line 1
$('#btn').click(function() { // Line 2
  window.z = 1               // Line 3
});
console.log(z)               // Line 5

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