GeeksforGeeks App
Open App
Browser
Continue

# Explain non-boolean value coercion to a boolean one in JavaScript

As we all know javascript is a forgiving language. It does not mind silly mistakes which programmers do. So, sometimes it gives unexpected results.  So it senses Javascript says “I can do every possibility”.

Coercion is one of those in which javascript gives weird results because javascript automatically performs type conversion in which first values get converted to other data types ( string, number, object, etc) then it gives result. Any type either it primitive  ( string, boolean, number, null, undefined, symbol ) or nonprimitive (object, array, reg exp)  coercion is valid.

Let’s understand how does Coercion work for different data types operations.

Example:

## Javascript

 ``

Output:

Explanation: Here for the first statement first operand [] is an object and the other is a string so both get coerced combined as a string and the same logic is applied in the statement inside if here also both coerced to a string. for a second if statement true first coerced to 1 then if block executes last example {} + {}, here both object so it concatenates as an object.

Boolean: A logical entity with values as ‘true’ and ‘false’.

For boolean conversion there are two ways:

1. !!: First it! it converted or coerced value to boolean opposite of value given then using double (!!) it gives boolean.
2. Boolean(): simply coerced value to desired boolean.

Example:

## Javascript

 ``

Output:

```true
true
false
true```

There are two types of coercion:

1. Implicit type coercion: Javascript itself does conversion to another data type automatically to give output as developer needs.
2. Explicit type coercion: Developer or programmer give type explicitly or say typecasting.

Example:

## Javascript

 ``

Output:

```number
boolean
number
number```

Falsy Values: Values that convert into boolean always gives true result.

There are six falsy values in javascript:

1. false
2. undefined
3. null
4. NaN (Not a number)
5. 0
6. ” ” (empty string)

Example:

## Javascript

 ``

Output:

```false
false
false
false
true
false```

Where does coercion not work in javascript while converting boolean?

The comparison operator (===) is known as the strict equality operator. (===)  coercion not work and (==) for this it works. It checks both the data type and the content. If the data type is not equal, it returns false. So “1” === 1 now evaluates to false . It gives results according to type it does trigger implicit type coercion.

Note: All the above examples can be tested by typing them within the script tag of HTML or using the console .

My Personal Notes arrow_drop_up
Related Tutorials