JS Type Conversion
In this page:
String(value);
Number(value);
Boolean(value);
parseInt(string);
Implicit vs Explicit Conversion
Implicit conversion, also called coercion, happens automatically when JavaScript needs values of matching types, like in + or ==, while explicit conversion is when you deliberately call a function like Number() to convert a value yourself.
उदाहरण: Implicit vs Explicit Conversion
console.log("5" + 1); // "51" - implicit coercion
console.log(Number("5") + 1); // 6 - explicit conversion
Number(), String(), and Boolean()
Number() converts a value to its numeric equivalent, String() converts a value into text, and Boolean() converts a value into true or false based on JavaScript's truthy and falsy rules.
उदाहरण: Number(), String(), and Boolean()
// Print `Number("42")` to the console
// Print `Number("42")` to the console
console.log(Number("42"));
// Print `String(42)` to the console
// Print `String(42)` to the console
console.log(String(42));
// Print `Boolean(0)` to the console
// Print `Boolean(0)` to the console
console.log(Boolean(0));
// Print `Boolean("hello")` to the console
// Print `Boolean("hello")` to the console
console.log(Boolean("hello"));
parseInt and parseFloat
parseInt() reads a string from the start and extracts a whole number, stopping at the first non-numeric character, and parseFloat() does the same but allows a decimal point in the result.
उदाहरण: parseInt and parseFloat
console.log(parseInt("42px")); // 42
console.log(parseFloat("3.14m")); // 3.14
Common Coercion Gotchas
A few JavaScript coercion rules are widely considered surprising, including Number('') returning 0, and NaN never being equal to itself, even with ===, which is why isNaN() or Number.isNaN() is required to properly detect it.
उदाहरण: Common Coercion Gotchas
console.log(Number("")); // 0
console.log(NaN === NaN); // false
console.log(isNaN(NaN)); // true
console.log(Number.isNaN(NaN)); // true
Converting Real Form Input
Values read from HTML form inputs, including type=number fields, always arrive as strings in JavaScript, making explicit conversion an essential step before performing any arithmetic on user-submitted data.
उदाहरण: Converting Real Form Input
const inputValue = "25"; // value read from a form input, always a string
const age = Number(inputValue);
console.log(age + 5);
Chapter Quiz — Complete all 26 topics to unlock
0/26 topics done
Complete these topics first:
- JS Dates
- JS Math
- JS Conditionals
- JS Switch
- JS Loop For
- JS Loop While
- JS Iterables
- JS Sets
- JS Maps
- JS typeof
- JS Type Conversion
- JS Destructuring
- JS Arrow Functions
- JS Classes
- JS Modules
- JS Promises
- JS Async/Await
- JS DOM
- JS DOM Methods
- JS Events Advanced
- JS DOM Navigation
- JS DOM Collections
- JS Async Callbacks
- JS Async Parallel
- JS Date Set
- JS Set Logic