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

Why Does \'1 1\' Sometimes Equal \'11\' in Javascript?

Linda Hamilton
Release: 2024-11-01 02:24:02
Original
382 people have browsed it

Why Does

Concatenation vs. Addition with the ( ) Operator in Javascript

When using the ' ' operator in Javascript, it's important to be aware of its dual nature, as it can be used for both concatenation and addition. This can lead to unexpected results, such as when trying to add numbers and instead getting a concatenated string.

Consider the following code:

<p>i = 1</p>
<p>divID = "question-" + i+1;</p>
Copy after login

This code would result in 'question-11' being assigned to 'divID', rather than the expected 'question-2'. This is because Javascript evaluates the expression from left to right, and 'i' is first concatenated to the string 'question-'.

To avoid this issue and correctly perform addition, use parenthesis to enforce the order of operations:

<p>divID = "question-" + (i+1);</p>
Copy after login

This forcesJavascript to evaluate the expression 'i 1' first, which results in the addition of 'i' and '1', giving us '2'. Then, this value is concatenated to the string 'question-', resulting in the correct output 'question-2'.

Remember that the ' ' operator can perform both concatenation and addition, and the order of operations can impact the result. Use parentheses to explicitly define the order of operations when combining numeric and string values.

The above is the detailed content of Why Does \'1 1\' Sometimes Equal \'11\' 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