HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Type Conversion

Type conversion is the process of converting a value from one data type to another (such as a string to a number). In JavaScript, this happens in two ways: Explicit (done manually by the developer) and Implicit (done automatically by JavaScript).


1. Explicit Type Conversion

Explicit conversion occurs when you manually use a JavaScript function to change a value's type.

Converting to Numbers

The global Number() method can convert strings or booleans to numbers.

Number("3.14")  // returns 3.14
Number(" ")     // returns 0
Number("")      // returns 0
Number("99 88") // returns NaN (Not a Number)
Number(true)    // returns 1
Number(false)   // returns 0

Converting to Strings

The global String() method or the toString() method can convert numbers or booleans to strings.

String(123)       // returns "123"
(100 + 23).toString() // returns "123"
String(false)     // returns "false"

2. Implicit Conversion (Coercion)

JavaScript is a very flexible language. If you try to operate on two different data types, JavaScript will often automatically convert one of them to make the operation work. This is called type coercion.

The Addition (+) Quirk

When adding a number and a string, JavaScript treats the plus sign as a concatenation operator and converts the number to a string.

let result = "5" + 2; 
console.log(result); // "52" (String)

Other Arithmetic Operators

Interestingly, for subtraction (-), multiplication (*), and division (/), JavaScript will convert the string to a number.

console.log("10" - 5);  // 5 (Number)
console.log("10" * "2"); // 20 (Number)
console.log("10" / 2);   // 5 (Number)

Automatic Type Conversion Table

Original Value 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
null 0 "null" false
undefined NaN "undefined" false
Tip: Understanding implicit conversion is the key to avoiding weird bugs in JavaScript, especially when handling data from HTML forms (which always comes in as a string).

Key Points to Remember

  • Explicit conversion is done manually (e.g., Number())
  • Implicit conversion happens automatically (coercion)
  • The + operator favors strings
  • The -, *, and / operators favor numbers
  • Empty strings and null convert to 0 when forced into a number context
  • undefined converts to NaN in a number context