1 Implicit Types Conversions
2 Primitive Type Conversions
3 Objects To Primitive Conversion
4 Explicit Types Conversions
1. Implicit Types Conversions
JavaScript is flexible about the type of values
- for example, if JavaScript expects a value of number type, it will try to convert the passed value to 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.
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 |
"false" |
0 |
new Boolean(false) |
|
|
string
"" "3.1" "three" |
true true |
3.1 NaN |
new String("3.1") new String("three") |
|
|
number
0 -0 NaN Infinity -Infinity 3 (finite, non zero) |
false false true true true |
"0" "NaN" "Infinity" "Infinity" "3" |
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
object.toString()on the object to be converted, if this fails the interpreter tries theo.valueOf()method. If the second attempt fails a TypeError is thrown. - the conversion to string happens when:
- you pass an object to a built-in function that expects a string argument
- you call the String() function and pass the object
- you interpolate the object into template literals
Object to number
- To convert an object to a number value, the JavaScript interpreter makes the same attempts, but in the opposite order.
Before, it tries to invoke the
object.valueOf()method. If this fails, it tries to invoke theobject.toString()method. If both the two attempts fail a TypeError is thrown. - the conversion to number happens when:
- you pass an object to a built-in function that expects a numeric argument
- you use a operator that expects numeric operands
The toString() and valueOf() methods
All object inherits the toString and valueOf methods from Object.prototype
- these two methods serve for object-to-primitive conversions
- the
Object.prototype.toString()method should return a string that represents the object - the
Object.prototype.valueOf()method should return a non-string primitive value (tipically a number) that represents the object
// the toString() method for Object class is not useful
// because it return the string "[object Object]"
let myObject = { name:"Joe", surname:"Bloggs" };
console.log(myObject.toString()); // "[object Object]"
// Some built-in classes redefine the default method
// 1 the Array class's toString converts each element to string and join them with a comma
let array = [1,2,3,4,5];
console.log(array.toString()); // "1,2,3,4,5"
// 2 the Function class's toString method converts user-defined functions to string of source code
let sum = function (num1, num2) { return num1+num2 }
console.log(sum.toString()); // "function sum(num1,num2){ return num1+num2 }"
// 3 the Date class's toString method converts dates into datetime strings
let xmas = new Date(2020, 11, 25);
console.log(xmas.toString()); // "Fri Dec 25 2020 00:00:00 GMT+0100 (Central European Standard Time)"
The Object.prototype.valueOf() method
// Objects are compound values and cannot be represented by a primitive value,
// so the valueOf() method for Object class returns the object itself
let myObject = {name:"Joe",surname:"Bloggs"};
console.log(myObject.valueOf()); // {name: "Joe", surname: "Bloggs"}
// Array and Function classes inherit the default method
let array = [1,2,3,4,5], sum = function (num1, num2) { return num1+num2 };
console.log(array.valueOf()); // [1, 2, 3, 4, 5]
console.log(sum.valueOf()); // ƒ (num1, num2) { return num1+num2 }
// the Date class redefines the valueOf method
// to return the number of milliseconds since January 1, 1970
let xmas = new Date(2020, 11, 25);
console.log(xmas.valueOf()); // 1608850800000
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.
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