2. What is type coercion in JavaScript and how does it work?
easy

Type coercion refers to the automatic conversion of one data type to another in JavaScript. It occurs whenever two or more values of different types are used in an expression that requires all values to be of the same type.


For example, consider the following code:

let x = 2 + "3";
console.log(x); // Output: 23

In this code, we add a number (2) and a string ("3") and assign the result to the variable x. However, JavaScript automatically converts the string value to a number before performing the addition operation, resulting in an output of 23. This is an example of type coercion.

Type coercion can also occur when two values are used in comparison operations that require both values to be of the same type. For example:

let y = 5 > "6";
console.log(y); // Output: false

In this code, we compare a number (5) and a string ("6") using the greater than operator >. However, JavaScript automatically converts the string value to a number before performing the comparison, resulting in an output of false. This is another example of type coercion.


It's important to note that type coercion can sometimes lead to unexpected results and errors in JavaScript, especially when working with complex expressions involving multiple data types. It's always a good practice to use explicit type checking and conversion whenever possible to avoid these issues.