SoFunction
Updated on 2025-04-06

Explanation of boolean boolean value usage learning and related techniques in JavaScript

Two basic Boolean types in JavaScript:


The boolean value true means "true", and false means "false". Typical relational operators will return the results of a Boolean value. In addition, numeric values ​​0, -0, null, NaN, undefined, and null characters ("") of special values ​​are all interpreted as false, while other values ​​are interpreted as true.

function isMonth(mon) {
  if ((mon >= 1) && (mon <= 12)) {
    return true;
  } else {
    return false;
  }
}
if (isMonth(mon)) {
  alert("OK");
} else {
  alert("Please enter the correct month.");
}

boolean = new Boolean(value)
Generates a boolean object. Set value to the initial value true or false . In order to conform to the idea that "all data types can generate objects" in object-oriented, JavaScript has prepared this class, but basically no one uses it.
xx = new Boolean(true);
All types in ECMAScript have values ​​equivalent to the two values ​​of true or false. You must convert a value to its corresponding Boolean.
Value, you can call the transformation function Boolean();

Boolean(NaN);//false
Boolean(0);//false
Boolean('');//false
Boolean(null);//false
Boolean(undefined)//false
PS: You can use the !! operator to convert the truthy or falsy value to a boolean value.
!!"" // false
!!0 // false
!!null // false
!!undefined // false
!!NaN // false
!!"hello" // true
!!1 // true
!!{} // true
!![] // true