Saturday, March 8, 2014

JavaScript Type Conversions

1. Implicit Types Conversions

JavaScript is flexible about the types of values it needs. When JavaScript expects a boolean value, you may supply a value of any type, and JavaScript will convert it automatically as it needs. If JavaScript wants a string, it will convert whatever value you give it to a string. If JavaScript wants a number, it will try to convert the value you give it to a number.

Truthy values and falsy values

The following six values convert to false and are also called falsy values:
undefined, null, 0, -0, NaN, ""
All other values (comprised any object and any array) convert to true and work like true.

Suppose that a variable obj holds either an object or the value null. You can test the non null explicitly:
if(obj !== null) {
  ...
}
or you could omit the not null checking relying on the fact that null is falsy and objects are truthy:
if(obj) {
  ...
}

Arithmetic Operators

Binary arithmetic (*, /, %, -) operators and unary arithmetic operators (+, -, ++, --) convert their operands to number.
"5" - "4" // -> 1
"5" * "4" // -> 20

The binary + operator

The binary + operator adds numeric operands or concatenates string operands.
If both operands are strings, then it concatenates the two strings, if both operands are numbers then it adds the two numbers.
 19  +  84  // -> 103
"19" + "84" // -> "1984"
In other cases a conversion is needed and is given priority to string concatenation, according to the following three steps.
  • If either of the operands is an object, the other operand is converted using a special object-to-primitive conversion.
  • After object-to-primitive conversion, if either of its operand is string the other is converted to string and concatenated.
  • If the none of the operands are object or string, they are converted to numbers and added.
// one operand is a string/object: conversion with toString() and concatenation 
"2" + 2    // = "2" + 2.toString() -> "22"
5 + {fName:'Joe', lName:'Bloggs'} // 5 + {fName:'Joe', lName:'Bloggs'}.toString() -> '5[object Object]'
// none of the operands are string/object: conversion with valueOf() and addition
true + false     // = true.valueOf() + false.valueOf() -> 1
10 + null        // = 10 + null.valueOf() = 10 + 0 -> 10
10 + undefined   // = 10 + undefined.valueOf() = 10 + NaN -> NaN 

2. Primitive Type Conversions

The following table summarizes how JavaScript interpreter automatically converts a type when it expects another one.


Primitive Value to boolean to string to number to Object
undefined
null
false
false
"undefined"
"null"
NaN
0
TypeError
TypeError
boolean
true
false
"true"
"false"
1
0
new Boolean(true)
new Boolean(false)
string
""
"3.1"
"three"
false
true
true
0
3.1
NaN
new String("")
new String("3.1")
new String("three")
number
0
-0
NaN
Infinity
-Infinity
3 (finite, non zero)
false
false
false
true
true
true
"0"
"0"
"NaN"
"Infinity"
"Infinity"
"3"
new Object(0)
new Object(-0)
new Object(NaN)
new Object(Infinity)
new Object(-Infinity)
new Object(3)

3. Objects To Primitive Conversions

Object to boolean
All objects converts to the primitive value true
Object to string
To convert an object to a string value the JavaScript interpreter invokes the method o.toString() on the object to be converted, if this fails the interpreter tries the o.valueOf() method. If the second attempt fails a TypeError is thrown.
Object to number
To convert an object to a number value the JavaScript interpreter make the same attempts, but it before tries invoking the o.valueOf() method and then the o.toString() method on the object to be converted. If both the two attempts fail a TypeError is thrown.

toString and valueOf methods of JavaScript objects

Special object-to-primitive conversion

The special object-to-primitive conversion is an algorithm used by == and + operators to compare operands of different types.
This algorithm converts all objects, except Date objects, to a number value by calling object's valueOf() method, dates are converted through their toString() method. If object's valueOf() method does not return an useful value, it calls object's toString() method.

4. Explicit Types Conversions

When you need to perform an explicit conversion, you use constructor functions such as Boolean(), Number(), String() and Object().

Converting to primitive values

console.log(Number("3")); // 3
console.log(String(false)); // "false"
console.log(Boolean([])); // true

Converting to Object

console.log(Object(3)); //  Number {[[PrimitiveValue]]: 3}
console.log(Object(true)); //  Boolean {[[PrimitiveValue]]: true}
console.log(Object(null)); // Object {}, a void object not TypeError
console.log(Object(undefined)); // Object {}, a void object not TypeError

Idiomatic expressions

You may find the following expressions used as shorthands for explicit conversions:
// ""+x for String(x) 
console.log(true); // true
console.log(""+true); // "true"
// +x for Number(x)
console.log("5"); // "5"
console.log(+"5"); // 5
// !!x for Boolean(x)
console.log("1"); // "1"
console.log(!!"1"); // true 

No comments :

Post a Comment