Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

191
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda