Javascript if-statement vs comparison

Is it true that if-statement JavaScript completes a condition in Boolean?

if(x) => if(Boolean(x))

Is it true that in comparison, JavaScript wraps comparison elements into numbers?

a == b => Number(a) == Number(b)
+3
source share
3 answers

Yes and no.

For the first part, yes , this is essentially what javascript does.

But for the latter, no . Not everything in JavaScript can be converted to a number. For instance:

Number('abc') // => NaN

And non-A-numbers are not equal:

NaN == NaN // => false

So something like this:

Number('abc') == Number('abc') // => false!

But this is really true when comparing equalities.

'abc' == 'abc' // => true

As a side note , it's probably best to use ===in JavaScript, which also checks the type of compared values:

0 == '0' // => true
0 === '0' // => false, because integer is not a string

=== .

+3
  • , true, x , Boolean(x).

  • , . , == a b . Number() , a b Number. :


>>> 0x2A == 42
true   // both 'a' and 'b' are numbers.

>>> "0x2A" == 42
true   // 'a' is a string whose number coercion is equal to 'b'.

>>> "0x2A" == "42"
false  // 'a' and 'b' are different strings.
+1

, if-statement JavaScript Boolean?

.

, JavaScript ?

.

JavaScript JavaScript.

if § 12.5 :

if () Statement else Statement

, , GetValue(), ToBoolean().

( . ), if Boolean. , JavaScript boolean (§ 9.2):

  • undefined null false.
  • false, ± 0 NaN, true.
  • false, , true .
  • true.

- GetValue() , § 8.7.1, , GetValue(), - ToBoolean().

== § 11.9.3.
, , ( ) , , . . , ( - ), , , 4 , , ToNumber(), ( , ).

, , , , .

+1
source

All Articles