1
x = 1;    
if(x = 10) {x = 1;} 
else {x = x + 1;}
alert (x);

The result is always 1, instead of 1,2,3...

4 Answers 4

9

Replace

if(x = 10) {x = 1;} 

with

if(x == 10) {x = 1;} 

Because x=10 returns 10, which in a test evaluates as true, and thus the code {x = 1;} is executed.

From the MDN about if...else :

Any value that is not undefined, null, 0, NaN, or the empty string (""), and any object, including a Boolean object whose value is false, evaluates to true when passed to a conditional statement

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

Comments

4
x = 1;    
if(x 

==

10) {x = 1;} 
    else {x = x + 1;}
    alert (x);

Comments

4

if condition should be checked like below

x=1;
if(x == 10)
{x = 1;}
else
{x = x+ 1;}
 alert(x)

Thanks

Comments

3
var x = 1;
x = (x == 10)? 1:x+=1;
alert(x);

Comments

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.