Home  >  Article  >  Web Front-end  >  Why does '1' 1 equal '11' in JavaScript, but '1' - 1 equal 0?

Why does '1' 1 equal '11' in JavaScript, but '1' - 1 equal 0?

Susan Sarandon
Susan SarandonOriginal
2024-11-19 02:27:03891browse

Why does

Understanding the Concatenation and Subtraction Differences in JavaScript

In JavaScript, handling the plus ( ) and minus (-) operators between strings and numbers differs, often leading to confusion. To clarify this behavior, let's delve into two examples:

console.log("1" + 1); // Output: "11"
console.log("1" - 1); // Output: 0

String Concatenation ( )

When using the plus operator between a string ("1") and a number (1), JavaScript performs string concatenation. In this case, it converts the numeric value to a string ("1") and appends it to the existing string ("1"), resulting in the output "11".

Numeric Subtraction (-)

However, when using the minus operator, JavaScript prioritizes numeric operations. Since subtraction cannot be performed on strings, it implicitly converts the second "1" (a string) to a number before performing the subtraction. Therefore, JavaScript subtracts 1 from the numeric 1, resulting in an output of 0.

Additional Note:

In JavaScript, the plus operator can be overloaded to perform either string concatenation or numeric addition, depending on the data types of the operands. However, the minus operator is strictly used for numeric subtraction, hence its distinct behavior when working with strings.

The above is the detailed content of Why does '1' 1 equal '11' in JavaScript, but '1' - 1 equal 0?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn