Javascript
Mamta Kumawat  

Why console.log(1 + ‘1’ – 1); is 10 in JavaScript?

JavaScript is a dynamic, loosely typed language, which means it automatically converts between data types in certain situations. This automatic conversion, called type coercion, can sometimes lead to unexpected results. In this blog post, we’ll break down the expression console.log(1 + '1' - 1) and explain what’s happening under the hood.

console.log(1 + '1' - 1);

1. What Happens When You Add a Number and a String?

The expression 1 + '1' is evaluated first.

  • JavaScript sees a number (1) and a string ('1').
  • When the + operator is used with a string and a number, JavaScript converts the number to a string and then concatenates the two.
  • So, 1 + '1' results in the string '11'.

2. What Happens When You Subtract a Number From a String?

Next, we have '11' - 1.

  • The - operator works with numbers, so JavaScript tries to convert the string '11' back to a number.
  • JavaScript successfully converts '11' to the number 11, and then performs the subtraction 11 - 1, resulting in 10.

3. Final Output:

10

4. Why Does This Happen?

  • The + operator, when used with a string, triggers string concatenation.
  • The - operator, on the other hand, triggers type coercion that converts the string back to a number (if possible).
  • This behavior is part of JavaScript’s flexible type system, but it can sometimes be surprising, especially when you mix numbers and strings.

5. Key Takeaways:

  • Type Coercion: JavaScript automatically converts values from one type to another when necessary, which can lead to unexpected results.
  • + vs. – Operators: The + operator is used for string concatenation when mixed with a string, while the - operator always tries to convert its operands to numbers.
  • Always be cautious when mixing types, especially with arithmetic operators like + and -. Knowing how JavaScript handles type coercion can help you avoid errors and ensure your code behaves as expected

Leave A Comment