JavaScript syntax: Difference between revisions

Content deleted Content added
m Primitive data types: {{code|lang=javascript|code=}}
m Boolean: {{mono}}
Line 333:
===Boolean===
 
[[JavaScript]] provides a [[Boolean data type]] with {{mono|true}} and {{mono|false}} literals. The {{mono|[[typeof]]}} operator returns the string {{mono|"boolean"}} for these [[primitive types]]. When used in a logical context, {{mono|0}}, {{mono|-0}}, {{mono|null}}, {{mono|NaN}}, {{mono|undefined}}, and the empty string ({{mono|""}}) evaluate as {{mono|false}} due to automatic [[type coercion]]. All other values (the [[complement (set theory)|complement]] of the previous list) evaluate as {{mono|true}}, including the strings {{mono|"0"}}, {{mono|"false"}} and any object. Automatic type coercion by the equality comparison operators (<code>==</code> and <code>!=</code>) can be avoided by using the type checked comparison operators (<code>===</code> and <code>!==</code>).
 
When type conversion is required, JavaScript converts {{mono|Boolean}}, {{mono|Number}}, {{mono|String}}, or {{mono|Object}} operands as follows:<ref>{{cite web | url=https://developer.mozilla.org/en/JavaScript/Reference/Operators/Comparison_Operators | title=Comparison Operators - MDC Doc Center | publisher=Mozilla | date=5 August 2010 | accessdate=5 March 2011}}</ref>
Line 368:
</syntaxhighlight>
 
The new operator can be used to create an object wrapper for a Boolean primitive. However, the {{mono|typeof}} operator does not return {{mono|boolean}} for the object wrapper, it returns {{mono|object}}. Because all objects evaluate as {{mono|true}}, a method such as {{mono|.valueOf()}}, or {{mono|.toString()}}, must be used to retrieve the wrapped value. For explicit coercion to the Boolean type, Mozilla recommends that the {{mono|Boolean()}} function (without {{mono|new}}) be used in preference to the Boolean object.
 
<syntaxhighlight lang="javascript">