JavaScript/Notes/TypeConversion: Difference between revisions
(37 intermediate revisions by 3 users not shown) | |||
Line 1: | Line 1: | ||
There are five primitive types in JavaScript | == Types == | ||
* Number | |||
* String | |||
* Boolean | |||
* Null | |||
* Undefined | |||
* Object | |||
There are five primitive types in JavaScript. Everything else is an object. | |||
Various operations in JavaScript require conversion | === Conversion === | ||
Various operations in JavaScript require conversion between primitive and object values. | |||
=== Converting to Boolean === | === Converting to Boolean === | ||
When evaluating any expression that requires a boolean value, | When evaluating any expression that requires a boolean value, a boolean value must be produced. This occurs with the internal <nowiki>[[ToBoolean]]</nowiki> | ||
[http://ecma-international.org/ecma-262/5.1/#sec-9.2 § 9.2)]. | |||
For example: | For example: | ||
<source lang="javascript"> | <source lang="javascript"> | ||
var n = 0; | var n = 0; | ||
if(n) { // false | if(n) { // [[ToBoolean]](0) = false | ||
} | } | ||
var t = !""; // true. Empty string is falsy. | var t = !""; // true. Empty string is falsy. | ||
var f = !"f"; // false. Non-empty strings are not falsy. | var f = !"f"; // false. Non-empty strings other than "0" are not falsy, here. | ||
Boolean(""); // false. | |||
</source> | </source> | ||
All numbers boolean-convert to true except for | All numbers boolean-convert to true except for <code>+/-0</code> and <code>NaN</code>. | ||
Boolean operators use type-conversion for the evaluation of their left hand | Boolean operators use type-conversion for the evaluation of their left-hand operand. | ||
<source lang="javascript"> | <source lang="javascript"> | ||
1 && 0; // 0. | 1 && 0; // 0. | ||
Line 26: | Line 36: | ||
NaN || 0; // 0; | NaN || 0; // 0; | ||
</source> | </source> | ||
[http://ecma-international.org/ecma-262/5.1/#sec-11.11 § 11.11] Binary Logical Operators | |||
<blockquote> | |||
The production LogicalANDExpression : LogicalANDExpression && BitwiseORExpression is evaluated as follows: | |||
# Let lref be the result of evaluating LogicalANDExpression. | |||
# Let lval be GetValue(lref). | |||
# If ToBoolean(lval) is false, return lval. | |||
# Let rref be the result of evaluating BitwiseORExpression. | |||
# Return GetValue(rref). | |||
</blockquote> | |||
All falsy values: | All falsy values: | ||
Line 37: | Line 57: | ||
</source> | </source> | ||
All other primitive values and all objects are truthy. | All other primitive values and all native ECMAScript objects are truthy. | ||
=== Converting to String === | === Converting to String === | ||
Line 48: | Line 68: | ||
</source> | </source> | ||
=== | <source lang="javascript"> | ||
String(15); // Calls ToPrimitive(input argument, hint String). | |||
</source> | |||
=== Conversion to Primitive === | |||
Mathematical unary and binary operators, as well as boolean operators require the operands to be converted to primitives. | |||
The Addition operator is used, the operands must be converted into primitive values. First, the interpreter calls the object's valueOf. If the result is a primitive value, then that value is used. | |||
'''Example:''' | |||
<source lang="javascript"> | <source lang="javascript"> | ||
var | var ob = { | ||
valueOf : function() { return 1; } | valueOf : function() { return 1; } | ||
}; | }; | ||
ob + 1; // 2. | |||
</source> | </source> | ||
Otherwise, if <code>''o''.valueOf</code> results in an object —and <code>Object.prototype.valueOf</code> does — the object's <code>toString</code> is called. | Otherwise, if <code>''o''.valueOf</code> results in an object —and <code>Object.prototype.valueOf</code> does — the object's <code>toString</code> is called ([http://ecma-international.org/ecma-262/5.1/#sec-8.12.8 § 8.12.8]). | ||
<source lang="javascript"> | <source lang="javascript"> | ||
var | var ob = { toString : function() { return "1"; } }; | ||
ob + 1; // "11". | |||
</source> | </source> | ||
When performing string concatenation ([http://ecma-international.org/ecma-262/5.1/#sec-11.6.1 § 11.6.1]) with an object, the object (or objects) must be converted to a primitive. [http://ecma-international.org/ecma-262/5.1/#sec-9.1 [[ToPrimitive]](§ 9.1)] with no hint acts as if the hint were Number, unless the object in question is a Date object, in which case it behaves as if the hint were String. | |||
[http://jsbin.com/eTAQaNoX/2/edit toString, valueOf, and concatenation] | '''Example:''' [http://jsbin.com/eTAQaNoX/2/edit toString, valueOf, and concatenation] | ||
=== Converting to Number === | === Converting to Number === | ||
Converting strings is a very common requirement and many approaches can be used. Any mathematical operator except the concatenation/addition operator will force type-conversion to number. | Converting strings is a very common requirement and many approaches can be used. Any mathematical operator except the concatenation/addition operator will force type-conversion to number. | ||
<source lang="javascript"> | |||
var d1 = new Date(NaN); | |||
var d2 = new Date(NaN); | |||
d1.setFullYear(2000); | |||
d2.setFullYear(2000); | |||
d1 >= d2; // true, conversion to number. | |||
d1 <= d2; // true, conversion to number. | |||
d1 == d2 // false, different objects. | |||
</source> | |||
== parseInt(s, radix) == | == parseInt(s, radix) == | ||
To force use of a particular base, use the radix parameter: < | To force use of a particular base, use the radix parameter: | ||
<source lang="javascript">parseInt("09", base) // base from 2 to 36.</source> | |||
If <code>radix</code> is omitted, the base is determined by the contents of the string. Any string beginning with <code>0x</code> or <code>0X</code> represents a hexadecimal number. A string beginning with a leading 0 may, in older implementations, be parsed as octal (as if raxix were 8), in ECMA-262 Ed 3 (octal digits are 0-7). If string <code>09</code> is converted to <code>0</code>. | If <code>radix</code> is omitted, the base is determined by the contents of the string. Any string beginning with <code>0x</code> or <code>0X</code> represents a hexadecimal number. A string beginning with a leading 0 may, in older implementations, be parsed as octal (as if raxix were 8), in ECMA-262 Ed 3 (octal digits are 0-7). If string <code>09</code> is converted to <code>0</code>. | ||
=== Primitive to Object === | <source lang="javascript"> | ||
Property access operation on string, number, and boolean primitives results in the creation of a temporary object. | var t = "0xf"; | ||
Number(t); // 15 | |||
+t; // 15 | |||
</source> | |||
<h4>Hex to RGB using parseInt</h4> | |||
<source lang="javascript"> | |||
var hex = "#ff00cc"; | |||
var rgb = "rgb(" + | |||
hex.substring(1).replace(/[\w]{2}/g, function(cc, m, off) { return parseInt(cc, 16) + (m===4?'':','); } ) | |||
+ ")"; | |||
</source> | |||
=== Primitive to Object with Property Accessors <code>.</code> and <code>[]</code> === | |||
Property access operation on string, number, and boolean primitives results in the creation of a '''temporary'' object, for the algorithm. | |||
<source lang="javascript"> | <source lang="javascript"> | ||
// Primitive to Object conversion. | // Primitive to Object conversion. | ||
true.toString(); // Boolean Object. | true.toString(); // creates a temporary Boolean Object. | ||
1.2.valueOf(); // Number object. | 1.2.valueOf(); // creates a temporary Number object. | ||
" foo ".trim(); // String Object. | " foo ".trim(); // creates a temporary String Object. | ||
// null.toString(); // TypeError | // null.toString(); // TypeError | ||
Line 87: | Line 144: | ||
</source> | </source> | ||
=== Type Checking == | See also: http://dhtmlkitchen.com/how-property-access-works/ | ||
=== Object Creation === | |||
<source lang="javascript"> | |||
// You'll never need these. | |||
new Object(1); // Results a Number object. | |||
new Object(true); // Results a Boolean object. | |||
new Object(""); // Results a String object. | |||
JSON.parse("{}"); // Results an Object object. | |||
</source> | |||
== Type Checking == | |||
Use sparingly. Avoid overloading with typechecking. | |||
=== The typeof Operator === | |||
<source lang="javascript"> | <source lang="javascript"> | ||
typeof someval; | typeof someval; | ||
</source> | </source> | ||
<table> | <table border="1"> | ||
<tr> | <tr> | ||
<th>Type <th>Result | <th>Type <th>Result | ||
<tr><td>Undefined <td>"undefined" | <tr style="background: #eee"><td>Undefined <td>"undefined" | ||
<tr><td>Null <td>"object" | <tr><td>Null <td>"object" | ||
<tr><td>Boolean <td>"boolean" | <tr style="background: #eee"><td>Boolean <td>"boolean" | ||
<tr><td>Number <td>"number" | <tr><td>Number <td>"number" | ||
<tr><td>String <td>"string" | <tr style="background: #eee"><td>String <td>"string" | ||
<tr><td>Object (native and doesn't implement <nowiki>[[Call]]</nowiki>) <td>"object" | <tr><td>Object (native or host and doesn't implement <nowiki>[[Call]]</nowiki>) <td>"object" | ||
<tr><td>Object (native or host and implements <nowiki>[[Call]]</nowiki>) <td>"function" | <tr style="background: #eee"><td>Object (native or host and implements <nowiki>[[Call]]</nowiki>) <td>"function" | ||
</table> | </table> | ||
Latest revision as of 18:35, 25 June 2014
Types[edit]
- Number
- String
- Boolean
- Null
- Undefined
- Object
There are five primitive types in JavaScript. Everything else is an object.
Conversion[edit]
Various operations in JavaScript require conversion between primitive and object values.
Converting to Boolean[edit]
When evaluating any expression that requires a boolean value, a boolean value must be produced. This occurs with the internal [[ToBoolean]] § 9.2).
For example: <source lang="javascript"> var n = 0; if(n) { // ToBoolean(0) = false }
var t = !""; // true. Empty string is falsy. var f = !"f"; // false. Non-empty strings other than "0" are not falsy, here. Boolean(""); // false. </source>
All numbers boolean-convert to true except for +/-0
and NaN
.
Boolean operators use type-conversion for the evaluation of their left-hand operand. <source lang="javascript"> 1 && 0; // 0. "" || 0; // 0. null || undefined; // undefined. undefined || 1; // 1. NaN || 0; // 0; </source> § 11.11 Binary Logical Operators
The production LogicalANDExpression : LogicalANDExpression && BitwiseORExpression is evaluated as follows:
- Let lref be the result of evaluating LogicalANDExpression.
- Let lval be GetValue(lref).
- If ToBoolean(lval) is false, return lval.
- Let rref be the result of evaluating BitwiseORExpression.
- Return GetValue(rref).
All falsy values: <source lang="javascript"> false "" null undefined 0 NaN </source>
All other primitive values and all native ECMAScript objects are truthy.
Converting to String[edit]
With the +
operator, when either operand is a string, concatenation is performed.
All native objects have a toString method. Number.prototype.toString(base) is special in that it takes a base
parameter.
<source lang="javascript"> 15..toString(16) </source>
<source lang="javascript"> String(15); // Calls ToPrimitive(input argument, hint String). </source>
Conversion to Primitive[edit]
Mathematical unary and binary operators, as well as boolean operators require the operands to be converted to primitives.
The Addition operator is used, the operands must be converted into primitive values. First, the interpreter calls the object's valueOf. If the result is a primitive value, then that value is used.
Example:
<source lang="javascript"> var ob = {
valueOf : function() { return 1; }
}; ob + 1; // 2. </source>
Otherwise, if o.valueOf
results in an object —and Object.prototype.valueOf
does — the object's toString
is called (§ 8.12.8).
<source lang="javascript">
var ob = { toString : function() { return "1"; } };
ob + 1; // "11".
</source>
When performing string concatenation (§ 11.6.1) with an object, the object (or objects) must be converted to a primitive. ToPrimitive(§ 9.1) with no hint acts as if the hint were Number, unless the object in question is a Date object, in which case it behaves as if the hint were String.
Example: toString, valueOf, and concatenation
Converting to Number[edit]
Converting strings is a very common requirement and many approaches can be used. Any mathematical operator except the concatenation/addition operator will force type-conversion to number.
<source lang="javascript">
var d1 = new Date(NaN);
var d2 = new Date(NaN);
d1.setFullYear(2000); d2.setFullYear(2000);
d1 >= d2; // true, conversion to number. d1 <= d2; // true, conversion to number. d1 == d2 // false, different objects. </source>
parseInt(s, radix)[edit]
To force use of a particular base, use the radix parameter: <source lang="javascript">parseInt("09", base) // base from 2 to 36.</source>
If radix
is omitted, the base is determined by the contents of the string. Any string beginning with 0x
or 0X
represents a hexadecimal number. A string beginning with a leading 0 may, in older implementations, be parsed as octal (as if raxix were 8), in ECMA-262 Ed 3 (octal digits are 0-7). If string 09
is converted to 0
.
<source lang="javascript"> var t = "0xf"; Number(t); // 15 +t; // 15 </source>
Hex to RGB using parseInt
<source lang="javascript"> var hex = "#ff00cc"; var rgb = "rgb(" +
hex.substring(1).replace(/[\w]{2}/g, function(cc, m, off) { return parseInt(cc, 16) + (m===4?:','); } )
+ ")"; </source>
Primitive to Object with Property Accessors .
and []
[edit]
Property access operation on string, number, and boolean primitives results in the creation of a 'temporary object, for the algorithm. <source lang="javascript"> // Primitive to Object conversion. true.toString(); // creates a temporary Boolean Object. 1.2.valueOf(); // creates a temporary Number object. " foo ".trim(); // creates a temporary String Object.
// null.toString(); // TypeError // undefined.toString(); // TypeError </source>
See also: http://dhtmlkitchen.com/how-property-access-works/
Object Creation[edit]
<source lang="javascript"> // You'll never need these. new Object(1); // Results a Number object. new Object(true); // Results a Boolean object. new Object(""); // Results a String object. JSON.parse("{}"); // Results an Object object. </source>
Type Checking[edit]
Use sparingly. Avoid overloading with typechecking.
The typeof Operator[edit]
<source lang="javascript"> typeof someval; </source>
Type | Result |
---|---|
Undefined | "undefined" |
Null | "object" |
Boolean | "boolean" |
Number | "number" |
String | "string" |
Object (native or host and doesn't implement [[Call]]) | "object" |
Object (native or host and implements [[Call]]) | "function" |