JavaScript/Notes/TypeConversion

From Noisebridge
< JavaScript(Difference between revisions)
Jump to: navigation, search
(Converting to Object)
(Converting to Boolean)
Line 18: Line 18:
 
All other numbers boolean-convert to true.
 
All other numbers boolean-convert to true.
  
Boolean operators type-convert their operands to boolean
+
Boolean operators use type-conversion for the evaluation of their left hand side operands.
<table>
+
<source lang="javascript">
<caption></caption>
+
1 &amp;&amp; 0; // 1.
<tr>
+
"" || 0; // 0.
<td>&amp;&amp;<td>|| <td>!
+
null || undefined; // undefined.
</tr>
+
undefined || 1; // 1.
</table>
+
NaN || 0; // 0;
 +
</source>
 +
 
 +
All falsy values:
 +
<source lang="javascript">
 +
false
 +
""
 +
null
 +
undefined
 +
0
 +
NaN
 +
</source>
  
 
=== Converting to String ===
 
=== Converting to String ===

Revision as of 21:44, 5 January 2014

There are five primitive types in JavaScript: Null, Undefined, Boolean, String, Number.

Various operations in JavaScript require conversion to and from primitive values.

Contents

Converting to Boolean

When evaluating any expression that requires a boolean value, the expression must be converted into a boolean using the internal [[ToBoolean]].

For example:

if(0) { // false
}
 
var t = !""; // Empty string is falsy.
var f = !"f"; // Non-empty strings are not falsy.

Falsy Numbers: +/-0 and NaN All other numbers boolean-convert to true.

Boolean operators use type-conversion for the evaluation of their left hand side operands.

1 &amp;&amp; 0; // 1.
"" || 0; // 0.
null || undefined; // undefined.
undefined || 1; // 1.
NaN || 0; // 0;

All falsy values:

false
""
null
undefined
0
NaN

Converting to String

When either operand is a string, the concatenation is performed.

Whenever the + operator is used, the operands must be converted into primitive values. First, the interpreter calls the object's valueOf to get a primitive value. If the result is a primitive value, then that value is used. Example:

var o = { 
  valueOf : function() { return 1; } 
};
o + 1; // 2.

Otherwise, the object's toString is called.

var o = { toString : function() { return "1"; } }
o + 1; // "11".

Converting to Number

Converting strings is a very common requirement and many methods can be used. Any mathematical operator except the concatenation/addition operator will force type-conversion to number.

Converting to Object

Property access operation on string, number, and boolean primitives results in the creation of a temporary object.

true.toString(); // Boolean Object.
1.2.valueOf(); // Number object.
" foo ".trim(); // String Object.
 
// null.toString(); // TypeError
// undefined.toString(); // TypeError

See also: http://dhtmlkitchen.com/how-property-access-works/

Personal tools