Aditya Singh
Aditya Singh

Reputation: 9612

== in JavaScript returns variable results for same condition

On changing the sequence of temp variable in the if condition returns variable results.

var temp=1;

var res=(temp++==temp)?"Equal":"Not Equal";
alert(res); //Not Equal

var res=(temp==temp++)?"Equal":"Not Equal";
alert(res); //Equal

JS Fiddle :- http://jsfiddle.net/adiioo7/e9qLK/

Upvotes: 0

Views: 66

Answers (3)

Alnitak
Alnitak

Reputation: 339816

It's very simple.

In the first, temp is incremented, but because it's a post increment operator the left-hand side (LHS) of the expression still evaluates to its original value. Then the right-hand side (RHS) is evaluated, but temp was already incremented, so it has the new value. Then the LHS and RHS are compared - they're no longer equal.

In the second example, the increment happens after the RHS is evaluated, so the LHS and RHS remain equal.

I wouldn't rely on this behaviour. In other languages ISTR it is explicitly undefined behaviour to refer to the same variable more than once in an expression when an increment operator is being used.

Upvotes: 1

user1919238
user1919238

Reputation:

It has to do with the order of operations. Here is what happens in the comparison:

  • Evaluate left side expression.
  • Evaluate right side expression.
  • See if the two are equal.

The postincrement operator (++) returns a value and then increments the variable by 1. So in your first case, the first temp has a value of 1, but it increments to 2 before the right side is evaluated. In the second case, the increment happens after the value of both sides is already obtained.

Note that this behavior is not true in all languages--implementations vary.

Upvotes: 1

Waleed Khan
Waleed Khan

Reputation: 11467

This is because ++ after the variable returns the value, then increments it.

So in the first example, temp++ on the left side is 1 but temp on the right side is 2.

In the second example, temp and temp++ are both 1.

Upvotes: 1

Related Questions