Home > Web Front-end > JS Tutorial > Why Does ' ' Concatenate Strings But '-' Subtracts Numbers in JavaScript?

Why Does ' ' Concatenate Strings But '-' Subtracts Numbers in JavaScript?

Patricia Arquette
Release: 2024-11-24 00:05:14
Original
451 people have browsed it

Why Does ' ' Concatenate Strings But '-' Subtracts Numbers in JavaScript?

Divergent Behavior of ' ' and '-' Operators with Strings and Numbers in JavaScript

JavaScript exhibits a puzzling behavior when performing mathematical operations between strings and numbers. Specifically, the behavior of the ' ' and '-' operators varies depending on the operand types involved.

Let's delve into two examples to illustrate this observation:

  1. String Concatenation ( ):

    console.log("1" + 1);
    Copy after login

    Output: "11"

  2. Number Subtraction (-):

    console.log("1" - 1);
    Copy after login

    Output: 0

Reasoning:

  1. String Concatenation: The ' ' operator performs string concatenation when one of the operands is a string. In the first example, "1" is a string, so JavaScript converts the numeric 1 to a string and concatenates them, resulting in "11".
  2. Number Subtraction: On the other hand, the '-' operator cannot perform subtraction on strings. Instead, JavaScript attempts to convert the string operand ("1" in the second example) to a number. This conversion succeeds because "1" can be validly interpreted as a numeric value. However, the resulting subtraction of 1 from 1 yields 0.

This behavior stems from the fact that JavaScript adheres to the "loose typing" paradigm, where type coercion is automatically performed to make operations compatible. However, in the case of the '-' operator and strings, type coercion cannot be applied, leading to the observed behavior.

The above is the detailed content of Why Does ' ' Concatenate Strings But '-' Subtracts Numbers in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template