Why the condition is false ? | SoloLearn: Learn to code for FREE!

+3

# Why the condition is false ?

i wrote these - var a=10; var b=20; result=(a==(b-=a))&&(b==(a+=a)); document.write(result); 4 lines of code in JavaScript and not getting expected result. why the condition is not true or why it's false ?

6/5/2018 6:32:49 PM

Ram Suthar

+6

By the way, let me explain one thing to you. I think it's why you were expecting a different result. (a==(b-=a)) ^In this part, (b-=a) is the equivalent of writing b = b - a. As you can see, you're not just subtracting from the variable temporarily, you're actually assigning the new value to that variable. = assigns a value to a variable and == compares the values of variables. So in (a == (b-=a)) you're assigning the value of 10 to your variable 'b' and then comparing 'a' and 'b' to see if they're equal to the same thing. In this case, they both equal 10 by the end of the comparison, so it's true. (b==(a+=a)) ^Just like in the other example, in this one you're comparing 'b' (which is now 10 instead of 20 because of the operation before) against 'a' after you assign a new value to 'a' (in this case, a+=a is a = 10 + 10, which is 20). By this point, 'b' is equal to 10 and 'a' is equal to 20, so that comparison returns false and the entire && condition returns false as a result.

+3

When in doubt, write it out! :) a = 10 b = 20 result = (10 == (10)) AND (10 == (20)) ^So as you can see, the first section is TRUE, while the second half is FALSE. Since we used && (AND), both sides have to be true for the condition to be true. Since only one side is true, the condition returns false.

+2

thnku Fata1 Err0r dude... got it. if i put 2nd condition before && and 1st condition after && then the second condition which was first before, become false... am i right ?

+2

@Ram Suthar You're welcome bro! I just posted up more of an explanation so you better understand what happened. Let me know if you need me to elaborate further or if you have any questions. More than happy to help you out.

+2

Fata1 Err0r thnku brother :)

+2

Here is what it looks like if you swapped around the conditions. Because you're assigning values in your condition, rather than only comparing values, you still end up with the second condition returning false, which causes the entire && (AND) to return false. If you want it to return true if one or the other is true, then use || (OR) instead of && (AND). var a =10; var b = 20; result = (b==(a+=a)) && (a==(b-=a)); result = (20 == (20)) && (20 == (0))

+2

You're more than welcome, Ram. I wish you the best with your learning! Post up if you run into anymore issues.

+2

Fata1 Err0r i was tired nd the way you responded is priceless... i got some extra energy to work... thnku once again bro 😊