Sobes.tech
Junior

Tell me about type conversion in JavaScript.

sobes.tech AI

Answer from AI

Type conversion in JavaScript occurs explicitly (forced) or implicitly (automatic, coercion).

Explicit conversion:

  • Is called explicitly by the developer.
  • Uses built-in functions or constructors: String(), Number(), Boolean(). Parse integer: parseInt(), parse float: parseFloat().
  • Examples:
// Conversion to string
let num = 123;
let str = String(num); // "123"

// Conversion to number
let strNum = "456";
let number = Number(strNum); // 456

// Conversion to boolean
let emptyStr = "";
let bool = Boolean(emptyStr); // false

Implicit conversion (Coercion):

  • Happens automatically by the JavaScript engine during operations.
  • Occurs in operators (arithmetic, comparison), in conditional expressions, when calling certain functions.
  • Examples:
// String concatenation
let result = "10" + 5; // "105" (number 5 is converted to string "5")

// Arithmetic operation
let result2 = "10" - 5; // 5 (string "10" is converted to number 10)

// Comparison
let result3 = "10" == 10; // true (string "10" is converted to number 10)

// In a conditional expression
if ("hello") {
  // String "hello" is converted to true
}

Rules of implicit conversion:

  • To string: When adding a string to any other type, everything is converted to a string.
  • To number: In arithmetic operations (except addition with a string), comparison operations (>, <, >=, <=), unary plus +, and when calling mathematical functions.
  • To boolean: In logical operators (||, &&, !), in conditional expressions (if, while). "Falsy" values: false, 0, "", null, undefined, NaN. Everything else is "truthy".
  • To primitive: Objects are converted to primitives when necessary. The conversion order depends on the context (ToPrimitive algorithm).
// Unary plus
let strNum = "123";
let num = +strNum; // 123

// Object comparison
[] == false; // true (both convert to 0)

Understanding type conversion is critical to avoid unexpected code behavior. Implicit conversion can be a source of errors, so explicit conversion is often preferred, making the code more predictable.

Tell me about type conversion in JavaScript. — Frontend - sobes.tech