-1

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?

1
  • 3
    if(num=2) is wrong - always true, I think you need if(num === 2) Commented Jun 6, 2018 at 15:41

1 Answer 1

2

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;
  }
}

Sign up to request clarification or add additional context in comments.

2 Comments

Here problem is a is not becoming 1 becz validate function is not completely exectued but while loop is moving to next iteration.
@ShanmukhaPhaneendraGajula , a becomes 1 when the condition in the if statement is true. What is the problem?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.