JavaScript Type Conversion Overview
JavaScript supports type conversion, allowing variables to be converted to new data types either explicitly using specific JavaScript functions or implicitly by JavaScript itself.
Converting Strings to Numbers
JavaScript provides the global Number() method to convert values into numbers. Here's how different inputs are handled:
- A numeric string like "3.14" is converted to the number 3.14.
- An empty string "" converts to 0.
- A non-numeric string like "John" converts to NaN (Not a Number).
Examples of conversions:
Number("3.14"); // Converts to 3.14
Number(Math.PI); // The constant PI as a number
Number(" "); // Converts to 0 because it's an empty space
Number(""); // Converts to 0
Examples of non-conversions:
Number("99 88"); // Returns NaN due to the space between numbers
Number("John"); // Returns NaN as "John" is not numerical
Number Conversion Methods
Several methods are available for converting strings to numbers, including:
- Number(): Converts its argument to a number.
- parseFloat(): Parses a string and returns a floating-point number.
- parseInt(): Parses a string and returns an integer.
Unary Plus Operator
The unary plus (+) operator can convert variables to numbers:
et y = "5"; // y is a string
let x = +y; // x is now a number (5)
If conversion isn't possible, it results in NaN:
let y = "John"; // y is a string
let x = +y; // x is NaN
Converting Numbers to Strings
The global String() method and the Number method toString() are used for converting numbers to strings:
String(123); // Returns "123"
(100 + 23).toString(); // Returns "123"
Converting Dates and Booleans
Dates to numbers: Both Number() and the Date method getTime() convert dates to milliseconds since January 1, 1970.
let d = new Date();
Number(d); // Milliseconds since the Unix epoch
d.getTime(); // Same as above
Dates to strings: Similar conversions apply using String() and Date.prototype.toString().
String(new Date()); // Converts to a string representation of the date
Booleans to numbers and strings:
Number(false); // Returns 0
String(true); // Returns "true"
false.toString(); // Returns "false"
Automatic Type Conversion
JavaScript will attempt to convert data types automatically in certain operations, which might not always lead to expected results:
"5" + null; // Returns "5null"
"5" + 2; // Returns "52"
"5" - 2; // Returns 3
Summary Table of JavaScript Type Conversions
This table illustrates the outcomes when converting different JavaScript values to numbers, strings, and booleans, highlighting some results that might be unexpected by programmers. Each value and its conversions provide insight into JavaScript's type coercion behavior in various contexts.