Home > Web Front-end > JS Tutorial > body text

Why Does JavaScript Concatenate Instead of Adding with the Plus ( ) Operator?

Linda Hamilton
Release: 2024-10-28 23:39:30
Original
906 people have browsed it

Why Does JavaScript Concatenate Instead of Adding with the Plus ( ) Operator?

Concatenation Versus Summation with the Plus ( ) Operator in JavaScript

A common issue encountered in JavaScript is the unexpected concatenation of variables instead of their intended summation when using the plus ( ) operator. For example, when the following code is executed, assuming i is initialized to 1:

divID = "question-" + i+1;
Copy after login

The result obtained is "question-11" instead of "question-2".

This phenomenon occurs because the plus ( ) operator handles both concatenation and addition. When applied to different types of operands, the operator prioritizes concatenation if one operand is a string. Therefore, the operations are processed left-to-right:

  1. "question-" i: Since "question-" is a string, concatenation occurs, resulting in "question-1".
  2. "question-1" 1: Again, concatenation occurs due to the string operand, yielding "question-11".

To obtain the desired summation, enclose the numeric expression in parentheses:

var divID = "question-" + (i+1);
Copy after login

This ensures that the addition of i and 1 is performed first, with the result (2) then concatenated with "question-". The outcome is "question-2" as intended.

This behavior is prevalent in various programming languages, not just JavaScript. It is essential to remember that the order in which operations are executed matters, particularly when dealing with multiple types of operands and operators. Using parentheses explicitly controls the order of evaluation, preventing unexpected results.

The above is the detailed content of Why Does JavaScript Concatenate Instead of Adding with the Plus ( ) Operator?. 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