Query about Javascript execution sequence

I have written the following code in JavaScript:

var num=1;
var a=0;
while(a==0){
  num +=1;
  //some logic
  //some logic

  validate();
  alert(num);
}

function validate(){
  //some logic
  //some logic
  if(num==2){
    a=1;
  }
  //some logic
  //some logic
}

Here I am getting alert of 1, 2, 3.. but a is not becoming 1. I have observed that validate(); function is not completed, but the execution is moved to next iteration. Could anyone help me figure this out?

Upvotes: -1

Views: 50

Answers (1)

Cory Kleiser
Cory Kleiser

Reputation: 2024

Your if statement is assigning a value to num not checking it. You have num=2 which will always be true, you need num===2.

Furthermore, if you would like to get 1, 2, then 3 you need to initially set num to 0 (var num=0;) and also check num against 3 instead of 2 in your if statement (num === 3)

Your updated code:

var num = 0;
var a = 0;
while (a === 0) {
  num += 1;
  validate();
  alert(num);
}

function validate() {
  if (num === 3) {
    a = 1;
  }
}

Upvotes: 2

Related Questions