Sunday, December 29, 2024
Google search engine
HomeLanguagesJavascriptExplain non-boolean value coercion to a boolean one in JavaScript

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




<script>
    if([]+"A")
    console.log([]+5);
    console.log("1"+2);
    if(true)
    console.log(false)
    console.log({ }+{ });
</script>


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




<script>
    // Boolean converted true first to 1
    // then it gives output true
    console.log(Boolean(true)) //true
 
    // String is constant variable storing string value
    const string = 'string';
     
    // y is constant variable coerced boolean
    // to constant variable string
    const y=!!string;
    console.log(y) //true
     
    // Here !(single exclamatory) on constant variable
    // y coerced true value to false.
    console.log(!y) //false
 
    // a is constant variable storing integer value
    const a=34
     
    // x is constant variable coerced boolean to
    // constant variable a
    const x=Boolean(34);
    console.log(x) //true
</script>


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




<script>
    // Implicit coercion
    console.log(typeof(5/null));
    console.log(typeof('2'== 2));
 
    // Explicit coercion
    const num = "124789";
    const a = Number(num);
    console.log(typeof(a));
    const b = 0 | null
    console.log(typeof(b))
</script>


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




<script>
    // Boolean conversion of empty string
    console.log(!!"");         // false
     
    // Boolean conversion of 0
    console.log(!!0);          // false
     
    // Boolean conversion of null
    console.log(Boolean(null));       // false
     
    // Boolean conversion of undefined
    console.log(Boolean(undefined));  // false
     
    // Opposite of boolean conversion
    // (true to false using single !) of not a number
    console.log(Boolean(!NaN));        // true
     
    // Boolean conversion of false
    console.log(!!false);      //false
</script>


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 .

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments