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

185
Visualizações
Unary + operator in JavaScript applied to ' ' (string with space)

I am confused by the following code:

Boolean(' '); // true
Boolean(''); // false
+' '; // 0
+''; // 0

My assumptions:

  1. Since Boolean(' ') evaluates to true, ' ' is a truthy value.
  2. Since Boolean('') evaluates to false, '' is a falsy value.
  3. Since the unary + operator attempts to convert its operand into a number, it should convert a falsy value to 0, and a truthy value to 1.

Question: Why does the unary + operator convert a truthy value (i.e. ' ') to 0?

Please feel free to point out everything that is wrong about my assumptions, and anything that I am missing. Thank you so much!

=================

EDIT AFTER INITIAL THREE REPLIES

Thank you guys, you are great, and your are right! Here's what I found in the ES6 specs:

"The conversion of a String to a Number value (...:) This value is determined in two steps: first, a mathematical value (MV) is derived from the String numeric literal; second, this mathematical value is rounded as described below. The MV on any grammar symbol, not provided below, is the MV for that symbol defined in 11.8.3.1.

The MV of StringNumericLiteral ::: [empty] is 0.

The MV of StringNumericLiteral ::: StrWhiteSpace is 0.

The MV of StringNumericLiteral ::: StrWhiteSpaceopt StrNumericLiteral StrWhiteSpaceopt is the MV of StrNumericLiteral, no matter whether white space is present or not."

(Source: https://262.ecma-international.org/6.0/#sec-runtime-semantics-mv-s)

So that would explain why both +'' and +' ' evaluate to 0.

I was also confused why Boolean() did not evaluate both to false:

The abstract operation ToBoolean converts argument to a value of type Boolean according to Table 10: (...) String: Return false if argument is the empty String (its length is zero); otherwise return true.

Source: https://262.ecma-international.org/6.0/#sec-toboolean

So that's why Boolean(''); // false and Boolean(' '); // true.

Thank you so much for your help! :)

about 4 years ago · Juan Pablo Isaza
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