Created
April 28, 2015 17:11
-
-
Save sagiavinash/4a5e64e64da83faa0fc9 to your computer and use it in GitHub Desktop.
Efficient Type Conversion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* General Statement: To convert values to a particular datatype use type coercsion instead of explicit conversion. */ | |
/* To Number */ | |
var val = "123"; | |
// 1. using Exclusing Type conversion. | |
console.log(Number(val)); | |
// 2. using Type Coercion (unary plus operator) | |
console.log(+val); | |
// among these methods the Type Coercion is fast. (http://jsperf.com/number-vs-unary-plus) | |
/* To String */ | |
var val = 123; | |
// 1. using Exclusing Type conversion. ( using toString() or String() ). | |
console.log(val.toString()); | |
// 2. using Type Coercion (appending empty string) | |
console.log(val+""); | |
// among these methods Type Coercion is fast. (http://jsperf.com/tostring-vs-append-empty-string) | |
/* To Boolean */ | |
var val = []; | |
// 1. using Exclusing Type conversion. | |
console.log(Boolean(val)); | |
// 2. using Type Coercion (applying not operator twice) | |
console.log(!!val); | |
// among these methods Type Coercion is fast. (http://jsperf.com/boolean-vs-double-not) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
123