Module 2: Variables, Data Types, Type Casting, and Comments
Type Casting and Conversion
Type conversion (or type casting) is the process of converting a value from one data type to another.
Implicit Conversion (Coercion): JavaScript often automatically converts values from one type to another when an operation involves mixed types. This can sometimes lead to unexpected results if not understood.
console.log("5" + 3); // Output: "53" (number 3 is coerced to string "3") console.log("5" - 3); // Output: 2 (string "5" is coerced to number 5) console.log(5 + true); // Output: 6 (boolean true is coerced to number 1) console.log(Boolean(0)); // Output: false (0 is falsy)
Explicit Conversion: You can explicitly convert types using built-in functions:
String()
orvalue.toString()
: Converts a value to a string.let num = 123; let strNum = String(num); // "123" console.log(typeof strNum); // "string"
Number()
: Converts a value to a number. If the value cannot be converted, it returnsNaN
.
Shorthand ways to convert to number:let str = "45.6"; let numStr = Number(str); // 45.6 console.log(Number("hello")); // NaN console.log(Number(true)); // 1 console.log(Number(false)); // 0
+value
(unary plus operator)parseInt(string, radix)
: Parses a string and returns an integer.parseFloat(string)
: Parses a string and returns a floating-point number.Boolean()
: Converts a value to a boolean. Values that convert tofalse
(falsy values):false
,0
,""
(empty string),null
,undefined
,NaN
. All other values convert totrue
(truthy values).console.log(Boolean("hello")); // true console.log(Boolean(0)); // false console.log(Boolean(undefined)); // false