1 min read

Javascript Type coercion with examples

In JavaScript, type coercion refers to the way in which the interpreter automatically converts values from one data type to another, as needed, during the execution of a program.

Here are a few examples of type coercion in JavaScript:

šŸ‘‰ When an operator is applied to operands of different types, the operands are often coerced to a common type before the operation is performed. For example:

console.log(1 + '2');  // Output: '12'

In this example, the number 1 is coerced to a string before it is concatenated with the string '2'.

šŸ‘‰ When a non-boolean value is used in a boolean context, it is coerced to a boolean. For example:

console.log(!!'hello');  // Output: true
console.log(!!'');       // Output: false

In these examples, the string 'hello' is coerced to the boolean value true, and the empty string is coerced to the boolean value false.

šŸ‘‰ When a function is called with too few or too many arguments, the missing arguments are filled in with the value undefined, and excess arguments are ignored. This is called "argument coercion". For example:

function greet(name) {
  console.log(`Hello, ${name}!`);
}

greet('Alice');  // Output: 'Hello, Alice!'
greet();         // Output: 'Hello, undefined!'
greet('Bob', 'Charlie');  // Output: 'Hello, Bob!'

šŸ‘‰ When an object is used in a context where a primitive value is expected, the object is coerced to a primitive value using the internal ToPrimitive operation. For example:

console.log(1 + {});  // Output: '1[object Object]'

In this example, the object {} is coerced to the string '[object Object]', which is then concatenated with the number 1 to produce the string '1[object Object]'.

šŸ‘‰ When the + operator is used to concatenate a string and a number, the number is coerced to a string before the concatenation is performed. For example:

console.log(3 + 4 + '5');  // Output: '75'

In this example, the numbers 3 and 4 are first summed to produce the number 7, which is then concatenated with the string '5' to produce the string '75'.

šŸ‘‰ When the == operator is used to compare a value to null or undefined, it performs a type coercion before performing the comparison. For example:

console.log(null == undefined);  // Output: true

In this example, the == operator first coerces both null and undefined to the same type (which is undefined), and then performs the comparison. Since both values are now of the same type and value, the comparison returns true.

I hope these examples help to further illustrate the concept of type coercion in JavaScript.