Back to course

Explicit Type Conversion (Parsing and Casting)

JavaScript: The Complete '0 to Hero' Beginner Course

25. Explicit Type Conversion

Explicit conversion (or 'casting') is when we intentionally use functions to convert values, instead of relying on JavaScript's automatic coercion.

1. Converting to Number

  • Number(value): Converts the entire value to a number. If it fails, returns NaN.
  • parseInt(string): Parses a string and returns an integer. Stops parsing at the first non-digit.
  • parseFloat(string): Parses a string and returns a floating-point number.

javascript let ageStr = '30'; let ageNum = Number(ageStr); console.log(typeof ageNum); // 'number'

console.log(parseInt('45px')); // Output: 45 console.log(parseInt('a45')); // Output: NaN

2. Converting to String

Use the .toString() method or the String() function.

javascript let num = 123; console.log(num.toString()); // Output: '123' console.log(String(true)); // Output: 'true'

3. Converting to Boolean

Use Boolean(value).

javascript console.log(Boolean(1)); // true console.log(Boolean('')); // false (Falsy value) console.log(Boolean(0)); // false (Falsy value)