Home  >  Article  >  Web Front-end  >  javascript boolean type conversion

javascript boolean type conversion

WBOY
WBOYOriginal
2023-05-20 22:55:37855browse

The Boolean type (Boolean) in JavaScript represents only two possible values: true or false. In programming, the Boolean type is very important because it is the basis for logical judgments.

In JavaScript, there are actually many values ​​that can represent Boolean types. Let’s introduce their Boolean type conversion rules one by one:

  1. String type
    For string type, the following situations will be converted to false:
  • Empty string: ''
  • String 0:'0'
  • Case-insensitive string true, false

All other strings will be converted to true.

  1. Number type
    For numeric type, the following cases will be converted to false:
  • 0
  • NaN
  • undefined

All remaining numbers will be converted to true.

  1. Object type
    For object type, all objects will be converted to true, including empty objects, arrays, functions, etc.
  2. undefined and null types
    For undefined and null types, they will be converted to false.

The following are some specific examples to illustrate these conversion rules:

Boolean('') // false
Boolean('0') // true
Boolean('false') // true
Boolean('hello') // true

Boolean(0) // false
Boolean(NaN) // false
Boolean(1) // true
Boolean(-1) // true

Boolean({}) // true
Boolean([]) // true
Boolean(function(){}) // true

Boolean(undefined) // false
Boolean(null) // false

It should be noted that when using double equal signs (==) for type comparison, JavaScript will Implicit Boolean type conversion. At this time, the following values ​​will be converted to false for comparison:

  • false
  • 0
  • ''
  • null
  • undefined
  • NaN

The remaining values ​​will be converted to true for comparison. For example:

'' == false // true
0 == false // true
null == false // false
undefined == false // false

To summarize, the Boolean type conversion rules in JavaScript are not difficult to remember, and you can just make a judgment based on the actual scenario. It should be noted that when performing implicit type conversion, avoid causing errors and try to use strict type comparison operators (such as the double equal sign problem).

The above is the detailed content of javascript boolean type conversion. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn