Is there any way (except Boolean method) for converting any data types to boolean? This is an interview question and I didn't answer it.
Asked
Active
Viewed 341 times
-2
-
possible duplicate of [How can I convert a string to boolean in JavaScript?](http://stackoverflow.com/questions/263965/how-can-i-convert-a-string-to-boolean-in-javascript) Or maybe one of the other of [today’s menu options](http://stackoverflow.com/search?q=javascript+convert+boolean) …? – CBroe Feb 26 '15 at 23:09
-
Not string all data types... – alex Feb 26 '15 at 23:12
-
Well fell free to make the search term more specific. – CBroe Feb 26 '15 at 23:14
3 Answers
2
Two Logical NOT !!
Logical not always returns a Boolean
value, regardless of the data type it’s
used on:
If the operand is an object, `false` is returned.
If the operand is an empty string, `true` is returned.
If the operand is a nonempty string, `false` is returned.
If the operand is the number 0, `true` is returned.
If the operand is any number other than 0 (including Infinity), `false` is returned.
If the operand is null, `true` is returned.
If the operand is NaN, `true` is returned.
If the operand is undefined, `true` is returned.
The logical NOT operator can also be used to convert a value into its Boolean equivalent. By using
two NOT operators in a row, you can effectively simulate the behavior of the Boolean() casting
function. The first NOT returns a Boolean value no matter what operand it is given. The second
NOT negates that Boolean value and so gives the true Boolean value of a variable. The end result is
the same as using the Boolean()
function on a value

Melih Altıntaş
- 2,495
- 1
- 22
- 35
0
The abstract operation that converts to a boolean is called ToBoolean
:
- Undefined:
false
- Null:
false
- Boolean: The result equals the input argument (no conversion).
- Number: The result is
false
if the argument is+0
,−0
, orNaN
; otherwise the result istrue
. - String: The result is
false
if the argument is the empty String (its length is zero); otherwise the result istrue
. - Object:
true
.
However, this operation is internal and not available.
But there are some workaround to use it:
-
!!variable;
-
variable ? true : false;
-
Boolean(variable)

Oriol
- 274,082
- 63
- 437
- 513