-1

I'm having a problem. when I declare a variable in the global area and then change it in a function, Since the javascript engine first read all of the code and then goes back and run it line by line, when I come to use the variable again after I changed it, it has the same value as it has in the start.

this is an example:

var num = 2;

document.getElementById("button").onclick(function(){
  num = 3;
});

console.log(num); // will log 2

if(num == 3){
    window.alert('hi!');// will never do the alert
} 

If I click the element with the #button id, it might change the variable num, but as I said - the javascript engine first reads all of the code and then execute it line bu line, so the result in the console.log will be 2, and not 3. the same goes for the condition part - it will never be true because in the end, num = 2 and not 3.

does anybody knows what can I do in order to use the updated value of the variable?

connexo
  • 41,035
  • 12
  • 60
  • 87
TheTechGuy
  • 44
  • 5
  • 3
    This is a basic logical flaw, the `if` condition runs **now**, the event handler runs **later**. – adeneo Dec 03 '16 at 20:05
  • So how do I make the if statement check for the condition all the time? using a while loop? or maybe other way? – TheTechGuy Dec 03 '16 at 20:12
  • @TheTechGuy Add the `if` check to the `onclick()` handler. – ThomasH Dec 03 '16 at 20:19
  • Use a custom setter and getter function like demonstrated in my answer. – connexo Dec 03 '16 at 20:23
  • @Felix Kling Basically OP asks how to observe changes to a variable. Thus it is not a duplicate as you marked. – connexo Dec 03 '16 at 20:33
  • @connexo: That's not how I interpret the question. – Felix Kling Dec 03 '16 at 20:36
  • Can you explain better what you are actually trying to achieve? What is the variable used for? Does it even need to be global / shared? – Felix Kling Dec 03 '16 at 20:37
  • *does anybody knows what can I do in order to use the updated value of the variable?* Also, I read it in his code line `if(num == 3){ do_sth(); }` which OP meant to achieve `ifEver(num==3) { do_sth(); }` – connexo Dec 03 '16 at 20:40
  • 1
    @FelixKling Also check comment #2 by OP: *So how do I make the if statement check for the condition all the time? using a while loop? or maybe other way?* – connexo Dec 03 '16 at 20:48
  • @connexo: Fair enough. Though that question might just originate from not understanding the original problem. E.g. if the variable is only changed in a single location, then there is no need for a complex solution. I hope the OP provides some more info about their actual use case. But if you are right, I guess it would be a duplicate of [Listening for variable changes in JavaScript or jQuery](http://stackoverflow.com/q/1759987/218196) – Felix Kling Dec 03 '16 at 20:51
  • @FelixKling Until then, the available evidence clearly points towards this not being an exact duplicate, so imo it should be re-opened. – connexo Dec 03 '16 at 20:52

4 Answers4

1

Basically this is what happens with your code when it runs :

var num = 2;
console.log (num); //2
if(num == 3 ) // FALSE it's 2 
{
window.alert('hi');//will not run 
} 

and when you press the button this happens

num = 3 ;

Basically the num variable changed but you didn't add any code to show this

So ?

document.getElementById("button").onclick(function(){
  num = 3;
console.log(num);//3
if(num == 3 ) // TRUE it's 3 
{
window.alert('hi');//will run
} 
});
a4w
  • 557
  • 5
  • 17
0

ok.. I think you need the updated value on the button click..

So your code will be something like this :-

var num = 2;

document.getElementById("button").onclick(function(){
  num = 3;
  updatedValue(num);
});

function updatedValue(a)
{
  this.a = a;
  console.log(this.a); // will log 3 now

  if(this.a === 3){
    window.alert('hi!');// will never do the alert
  } 
}

You need to bind it in a function for smoother flow.

ThomasH
  • 19,270
  • 9
  • 53
  • 57
Neel Gala
  • 1,970
  • 17
  • 20
0

It has nothing to do with the JS engine reading and evaluating statements. It is directly in your code.

With onClick() you are just registering a handler. The code in the function you pass is not run yet. After registering the handler num is unchanged, and your code runs with the value of 2.

To see the change you have to click the button in the browser. After that you will see the new value, e.g. put the conditional alert in the handler function, and you will get the 'hi!' alert.

ThomasH
  • 19,270
  • 9
  • 53
  • 57
0

Making a value "observable" in JS

Wrapping your value in an object and then define a custom property getter and setter:

var num = {
  _val: 2,
  set val(value) {
    this._val = value;
    // Additional code that you want executed every time a value is assigned to num.val:
    if (value === 3) {
      console.log("num.val changed to 3");
      showVal();
    }
  },
  get val() {
    return this._val;
  }
};

function showVal() {
  console.log("num.val: " + num.val);
}

window.onload = function() {
    document.getElementById("button").addEventListener('click', function() {
      num.val = 3;
    });
};

showVal(); // will log 2
<button id="button">Change num.val to 3</button>

For more reference on this check MDN.

Community
  • 1
  • 1
connexo
  • 41,035
  • 12
  • 60
  • 87