If I use two negation operators on a string am I using type coercion?

71 views Asked by At

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?

3

There are 3 answers

0
wastl On BEST ANSWER

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?

2
Andre Pena On

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.

1
david_hughes On

!!(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. ;-)