Explain Type Coercion by examples in JS.
Answer: Type coercion in JavaScript refers to the automatic conversion of values from one data type to another. This happens when an operator or function requires a certain type of data that differs from the data type provided. Here are some examples of type coercion in JavaScript:
1. String and Number Concatenation:
var x = 5;
var y = "10";
var result = x + y; // JavaScript converts x to string and concatenates: "510"
console.log(result); // Outputs "510"
2. Comparison Operators:
var a = 10;
var b = "10";
if (a == b) {
console.log("Equal"); // JavaScript converts b to number and compares: "Equal"
}
3. Boolean Contexts:
var c = 0;
var d = "0";
if (c == false) {
console.log("c is falsy"); // JavaScript treats 0 as falsy
}
if (d == false) {
console.log("d is falsy"); // JavaScript converts "0" to number and treats as falsy
}
4. Truthy and Falsy Values:
var e = "Hello";
if (e) {
console.log("e is truthy"); // JavaScript treats non-empty strings as truthy
}
var f = "";
if (!f) {
console.log("f is falsy"); // JavaScript treats empty strings as falsy
}
5. Implicit Conversion in Functions:
function greet(name) {
name = name || "Anonymous";
console.log("Hello, " + name);
}
greet(); // Outputs: "Hello, Anonymous" (undefined coerced to string "Anonymous")
greet("Alice"); // Outputs: "Hello, Alice"
In these examples, JavaScript automatically converts values between strings, numbers, and booleans to perform operations or comparisons. Understanding type coercion is crucial for writing JavaScript code that behaves predictably, especially when working with different data types and operators.
No comments:
Post a Comment