JavaScript Type Conversion
JavaScript Type Conversion
Section titled “JavaScript Type Conversion”JavaScript is a dynamically typed language. Variables are not directly associated with a type; values are. Type conversion (or coercion) happens when an operator or function expects a value of a certain type but receives a value of a different type. JavaScript provides explicit conversion functions like Number(), String(), and Boolean().
JavaScript Data Types
Section titled “JavaScript Data Types”JavaScript has the following primitive data types:
string: Represents textual data.number: Represents numeric values (both integers and floating-point).boolean: Representstrueorfalse.null: Represents the intentional absence of any object value.undefined: Represents a variable that has not been assigned a value.symbol(ES6): Represents a unique identifier.bigint(ES2020): Represents integers with arbitrary precision.
And one non-primitive (complex) data type:
object: Represents collections of key-value pairs or more complex entities. This includesArray,Date,Function, and regular objects.
The typeof Operator
Section titled “The typeof Operator”Use the typeof operator to find the data type of a JavaScript value or variable.
typeof "John"; // Returns "string"typeof 3.14; // Returns "number"typeof NaN; // Returns "number" (NaN means Not-a-Number, but its type is number)typeof false; // Returns "boolean"typeof [1, 2, 3, 4]; // Returns "object"typeof {name:'John'}; // Returns "object"typeof new Date(); // Returns "object"typeof function() {}; // Returns "function" (functions are technically objects, but typeof has a special return for them)typeof myUndeclaredVar; // Returns "undefined" (if myUndeclaredVar is not declared or is declared and unassigned)typeof null; // Returns "object" (this is a long-standing quirk in JavaScript)typeof Symbol('id'); // Returns "symbol"typeof 100n; // Returns "bigint"Key observations:
- The data type of
NaNis"number". - The data type of an array is
"object". - The data type of a date is
"object". - The data type of
nullis"object"(a historical bug that’s unlikely to be fixed). - The data type of an undeclared or uninitialized variable is
"undefined".
To specifically check if a value is an array, use Array.isArray(value). To check if an object is an instance of a particular class (e.g., Date), use value instanceof Date. |
|---|
The constructor Property
Section titled “The constructor Property”Most JavaScript values (except null and undefined) have a constructor property that returns the constructor function that created the instance’s prototype.
"John".constructor; // Returns function String() { [native code] }(3.14).constructor; // Returns function Number() { [native code] }false.constructor; // Returns function Boolean() { [native code] }[1,2,3,4].constructor; // Returns function Array() { [native code] }({name:'John'}).constructor; // Returns function Object() { [native code] }(new Date()).constructor; // Returns function Date() { [native code] }(function() {}).constructor; // Returns function Function() { [native code] }While constructor can be inspected, for reliable type checking, prefer typeof, instanceof, or specific methods like Array.isArray().
Example of modern type checking:
function isArray(value) { return Array.isArray(value);}
function isDate(value) { return value instanceof Date && !isNaN(value);}
console.log(isArray([1, 2])); // trueconsole.log(isDate(new Date())); // trueExplicit Type Conversion
Section titled “Explicit Type Conversion”JavaScript variables can be explicitly converted to another data type using global functions:
String(value): Converts a value to a string.Number(value): Converts a value to a number.Boolean(value): Converts a value to a boolean.
JavaScript also performs automatic (implicit) type conversion in certain situations.
Converting to String
Section titled “Converting to String”The String() global function can convert numbers, booleans, and dates to strings.
String(123); // returns "123"String(100 + 23); // returns "123"String(false); // returns "false"String(true); // returns "true"String(new Date()); // returns a string representation of the date, e.g., "Mon Jul 22 2024 ..."Most values also have a toString() method:
(123).toString(); // "123"false.toString(); // "false"(new Date()).toString(); // String representation of the dateNumber-to-string methods like toExponential(), toFixed(), and toPrecision() offer more control over formatting.
| Method | Description |
|---|---|
| toExponential(fractionDigits?) | Returns a string, with a number rounded and written using exponential notation. |
| toFixed(digits?) | Returns a string, with a number rounded and written with a specified number of decimals. |
| toPrecision(precision?) | Returns a string, with a number written with a specified length (total number of significant digits). |
Converting to Number
Section titled “Converting to Number”The Number() global function converts values to numbers.
Strings containing valid numeric representations (like “3.14”) convert to numbers (like 3.14). Empty strings or strings with only whitespace convert to 0. Other non-numeric strings convert to NaN.
Number("3.14"); // returns 3.14Number(" "); // returns 0Number(""); // returns 0Number("99 88"); // returns NaNNumber("abc"); // returns NaNNumber(false); // returns 0Number(true); // returns 1Number(new Date());// returns timestamp (milliseconds since epoch)The parseInt(string, radix) and parseFloat(string) functions are also used to convert strings to numbers. Always specify the radix (base) for parseInt (usually 10 for decimal).
| Method | Description |
|---|---|
| parseFloat(string) | Parses a string and returns a floating point number. Stops at the first non-digit character. |
| parseInt(string, radix?) | Parses a string and returns an integer. A radix (e.g., 10 for decimal, 2 for binary) should be specified. |
The unary + operator is a concise way to convert a value to a number:
const y = "5";const x = +y; // x is the number 5
const z = "John";const w = +z; // w is NaNConverting to Boolean
Section titled “Converting to Boolean”The Boolean() global function converts values to booleans.
Values that convert to false (falsy values) are: false, 0, -0, 0n (BigInt zero), "" (empty string), null, undefined, and NaN.
All other values, including any object, non-empty array, non-empty string, and non-zero number, convert to true (truthy values).
Boolean(0); // falseBoolean(""); // falseBoolean(null); // falseBoolean(undefined); // falseBoolean(NaN); // false
Boolean(1); // trueBoolean("hello"); // trueBoolean({}); // trueBoolean([]); // trueAutomatic (Implicit) Type Conversion
Section titled “Automatic (Implicit) Type Conversion”JavaScript often performs type conversion automatically when operators are used with mixed types.
The results can sometimes be unexpected:
5 + null; // returns 5 (null is converted to 0)"5" + null; // returns "5null" (null is converted to "null")"5" + 2; // returns "52" (2 is converted to "2")"5" - 2; // returns 3 ("5" is converted to 5)"5" * "2"; // returns 10 (both "5" and "2" converted to numbers)5 == "5"; // returns true (string "5" converted to number 5 for comparison with ==)To avoid unexpected behavior with ==, it’s highly recommended to use the strict equality operator === which checks for both value and type equality without performing type coercion.
Automatic String Conversion in Output
Section titled “Automatic String Conversion in Output”When an object or variable is used in a context that expects a string (e.g., setting element.textContent), JavaScript automatically calls its toString() method (or valueOf() if applicable).
// Consider myVar assigned different values:// let myVar = {name:"John"}; // .toString() typically converts to "[object Object]"// let myVar = [1,2,3,4]; // .toString() converts to "1,2,3,4"// let myVar = new Date(); // .toString() converts to a date string like "Mon Jul 22 2024..."// let myVar = 123; // .toString() converts to "123"// let myVar = true; // .toString() converts to "true"
// Example with DOM element:// const demoElement = document.getElementById("demo");// if (demoElement) demoElement.textContent = myVar;JavaScript Type Conversion Table Summary
Section titled “JavaScript Type Conversion Table Summary”This table shows the result of converting various JavaScript values to Number, String, and Boolean using explicit conversion functions.
OriginalValue | Converted to Number | Converted to String | Converted to Boolean----------------|---------------------|---------------------|---------------------`false` | `0` | `"false"` | `false``true` | `1` | `"true"` | `true``0` | `0` | `"0"` | `false``1` | `1` | `"1"` | `true``"0"` | `0` | `"0"` | `true``"1"` | `1` | `"1"` | `true``NaN` | `NaN` | `"NaN"` | `false``Infinity` | `Infinity` | `"Infinity"` | `true``-Infinity` | `-Infinity` | `"-Infinity"` | `true``""` (empty str)| `0` | `""` | `false``"20"` | `20` | `"20"` | `true``"twenty"` | `NaN` | `"twenty"` | `true``[]` (empty arr)| `0` | `""` | `true` (arrays are objects)`[20]` | `20` | `"20"` | `true``[10,20]` | `NaN` | `"10,20"` | `true``{}` (empty obj)| `NaN` | `"[object Object]"` | `true` (objects are truthy)`null` | `0` | `"null"` | `false``undefined` | `NaN` | `"undefined"` | `false`Values in quotes indicate string values. Understanding these conversions is crucial for debugging and writing robust JavaScript code.