6

I was stumbling around trying different conditions, when I discovered ==-, or ==+.

In a JS console, you can write:

var a = " ";

then the following is true

a == " ";

but this is false

a == "    ";

However, it will be true if you say:

a ==- "   ";

or

a ==+ "   ";

So what is this nifty ==- operator?

elclanrs
  • 92,861
  • 21
  • 134
  • 171

3 Answers3

9

They're not distinct operators.

Writing:

a ==- " ";

gets parsed as:

(a) == (-" ");

The same goes for ==+.

The expression evaluates to true because of Javascript's weird type conversion rules. Something like the following occurs:

  1. the unary - (or +) operators converts its operand to a number. If it's a blank string, the result of this conversion is 0.
  2. a == (-" ") is then equivalent to " " == 0. If types compared with == are different, one (possibly both), get converted to get a common type. In this case, the " " on the left-hand side gets converted to 0 too.
  3. You end up comparing 0 to 0, which yields true.

(The above is a rough example of how Javascript might come to this result, the actual rules are buried in the ECMAScript specification. You can use the === operator instead to prevent the conversions and get false if the types of the compared objects are different.)

millimoose
  • 39,073
  • 9
  • 82
  • 134
3

It's simply a == followed by a - (or +).

(In the following I write "<four spaces>" to mean the string consisting of four spaces.)

That is, if you do " " ==- "<four spaces>", you compare " " to -"<four spaces>". -"<four spaces>" evaluates to 0, since applying the minus converts to integer. Thus, you actually do " " == 0, which is true, since it converts the " " to an integer for the comparison.

" " == "<four spaces>" is false, however, as you're comparing two different strings.

Sebastian Paaske Tørholm
  • 49,493
  • 11
  • 100
  • 118
1

That is NOT an operator. You get those results because - and + is casting the string to a number, in this case, an empty string casts to the number 0 which is then interpreted as false, plus the equals operator == will cause some trouble with comparison and casting, that's why it's recommended to always use the === operator and you'll get the results you're after:

console.log(a === ' '); // true
console.log(a === '   '); // false
console.log(a === -'   '); // false
console.log(a === +'   '); // false
elclanrs
  • 92,861
  • 21
  • 134
  • 171