1

Consider the following code:

!!('foo');

The negation operator uses the abstract operation ToBoolean to perform a type conversion, but my question is - does this involve type coercion?

Ben Aston
  • 53,718
  • 65
  • 205
  • 331

3 Answers3

2

According to wikipedia http://en.wikipedia.org/wiki/Type_conversion " the word coercion is used to denote an implicit conversion", so yes there is type coercion involved, since the conversion is enforced.

Alo take a look at the answer to this question What is the difference between casting and coercing?

Community
  • 1
  • 1
wastl
  • 2,643
  • 14
  • 27
1

Considering that coercion is simply an implicit conversion, that being either a cast or any kind of processed conversion, than yes, this involves coercion, because you didn't convert it explicitly.

Andre Pena
  • 56,650
  • 48
  • 196
  • 243
  • So type coercion is not a specific feature of JavaScript per se, but a behavior associated with certain operators in JavaScript (and other languages). – Ben Aston Dec 03 '14 at 12:59
  • 2
    Exactly. Any language can implement coersion. C#, for instance, even allows you to override operators in such a way that you can "control" coercions. – Andre Pena Dec 03 '14 at 13:00
0

!!(x) appears to return the same result as Boolean(x). You can see this for yourself by typing the following into the JavaScript console:

Boolean(false) === !!(false)
Boolean(0) === !!(0)
Boolean("") === !!("")
Boolean(null) === !!(null)
Boolean(undefined) === !!(undefined)
Boolean(NaN) === !!(NaN)

All over values are 'truthy' in JavaScript. Haven't checked every other available value in JavaScript; that could take some time. ;-)

david_hughes
  • 712
  • 2
  • 7
  • 9