What is the difference between explicit and implicit type conversion?
The earlier questions in this topic covered the basic types that JavaScript has and how the typeof operator reports them. This answer looks at what happens when a value of one type has to become a value of another type, and it is a good idea to understand because JavaScript does this quietly in many places.
There are two kinds of conversion. An implicit conversion happens when the engine decides on its own to change a value, usually because an operator received a type that it could not use. An explicit conversion happens because you called a function that says what it wants. The first one is the language being helpful, and the second one is you being clear.
// Implicit: the engine chooses the conversion for you.
console.log('10' * 2); // 20
console.log('10' + 2); // '102'
console.log(1 + null); // 1
// Explicit: you ask for the conversion by name.
console.log(Number('10')); // 10
console.log(String(10)); // '10'
console.log(Boolean(0)); // false
console.log(parseInt('10px', 10)); // 10
The explicit functions are the ones that you should reach for. Number converts text into a number, and it gives you a value that is not a number when the whole text is not numeric. String converts anything into text, including arrays and objects. Boolean applies the truthiness rules and gives you a real boolean. parseInt and parseFloat convert the numeric part at the start of a text value.
There are also some methods that belong to a value itself and that are worth knowing. The toFixed method on a number gives you a text value with a fixed number of decimal places. The toPrecision method gives you a text value with a given total number of important digits. The toString method takes a base, so you can turn the number 10 into base 36 or base 2.
The most useful place for explicit conversion is at the boundary of your program. A form field, a query string parameter, and a JSON payload can all give you text where you expected a number or a boolean. If you convert once, at the point where the data enters your program, then the rest of your code can rely on the types and never has to think about coercion again.