Recent Post:
Categories:
Type coercion is a process where JavaScript automatically converts one data type into another when performing operations. This can happen in various situations, and understanding it can help prevent unexpected behavior in your code. Think of it like a magic trick that changes one thing into another!
1. Primitive Types: String: Text (e.g., "Hello") Number: Numeric values (e.g., 42) BigInt: Very large numbers (e.g., 12345678901234567890n) Boolean: true or false Undefined: A variable that has been declared but not assigned a value Null: Represents no value or an empty value
2. Non-Primitive Type: Object: Collections of key-value pairs (e.g., {name: "Satyendra", age: 25})
1. Coercion with Strings and Numbers When a string is involved in an operation with a number, JavaScript usually converts the number to a string.
code
let result = "5" + 3; // Output: "53"
Here, 5 (number) is converted to "5" (string), and the result is "53".
code
let result = "5" - 3; // Output: 2
In this case, the string "5" is converted to the number 5, and the result is 2.
When a boolean is used in an operation, it gets coerced to a number: true becomes 1 and false becomes 0.
code
let result = true + 5; // Output: 6
true is converted to 1, so 1 + 5 equals 6.
code
let result = false + 5; // Output: 5
Here, false becomes 0, so 0 + 5 equals 5.
null and undefined have unique behaviors when coerced.
code
console.log(null == undefined); // Output: true
null and undefined are considered equal when using == (loose equality), but not with === (strict equality).
code
console.log(null + 1); // Output: 1
console.log(undefined + 1); // Output: NaN
null is treated as 0, so null + 1 equals 1. undefined is not a number, so undefined + 1 results in NaN (Not a Number).
When objects are involved, JavaScript tries to convert them to primitive types.
code
let obj = { value: 10 };
console.log(obj + 5); // Output: "[object Object]5"
The object is coerced to a string, resulting in "[object Object]", and then concatenated with 5.
code
let obj = { value: 10 };
console.log(obj - 5); // Output: NaN
When trying to subtract, the object cannot be converted to a number, resulting in NaN.
Strings and Numbers: Strings can convert numbers to strings during concatenation, while numbers can convert strings to numbers during arithmetic operations.
Booleans: true becomes 1 and false becomes 0.
Null and Undefined: null is equal to undefined with ==, but they are different with ===. null behaves like 0, while undefined leads to NaN in arithmetic.
Objects: When objects are involved, they are converted to strings or numbers based on the context.