Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

190
Views
Please explain this forcing string comparison code

How do I read String comparison can be forced by: "" + a == "" + b from https://262.ecma-international.org/5.1/#sec-11.9.6?

  1. I don't know the correct order of evaluating this (left-right or inside-outside)
  2. What are the intermediate conversions and values that lead to the final result?
  3. What are the concepts involved in those intermediate conversions, and are there other methods (less shorthand ways like Number() instead of unary +) to implement those conversions to make it more readable to a beginner?
  4. When is such a pattern used (why force string comparison, why force it this way assuming there are other ways) and are there pitfalls?
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

MDN has a table of operator precedence.

Addition (string and arithmetic) happens before equality. All else being equal, things are done left to right.

So given:

"" + a == "" + b

first "" + a is evaluated and is equivalent to String(a).

Then "" + b is evaluated and is equivalent to String(b).

The two results are then compared using ==.

It's used because it's less to write than String(a).

Whether Number(a) is more readable than +a is moot. There are things to learn about both. For conversion to number there is also parseInt, parseFloat and multiplication by 1, so all the following:

parseInt(a) 
parseFloat(a) 
+a
a * 1

might all give the same result (e.g. where a is an integer string like 10). But might not for other values (like '10.6'). Conversion to number is also complicated by NaN, so if either or both expressions resolve to NaN, then they don't equal each other ('cos NaN isn't == or === to any value, even itself).

Have fun. :-)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!