Skip to content

Instantly share code, notes, and snippets.

@sagiavinash
Created April 28, 2015 17:11
Show Gist options
  • Save sagiavinash/4a5e64e64da83faa0fc9 to your computer and use it in GitHub Desktop.
Save sagiavinash/4a5e64e64da83faa0fc9 to your computer and use it in GitHub Desktop.
Efficient Type Conversion
/* 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)
@jaydenrw222
Copy link

123

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment