Home >Web Front-end >JS Tutorial >The difference between ++i and i++ in js

The difference between ++i and i++ in js

下次还敢
下次还敢Original
2024-05-01 04:48:141130browse

The increment operator i in JavaScript first increments the variable value and then returns the incremented value, while i first returns the variable value and then increments it. Usage scenarios: If you need to use the variable value before incrementing, use i; if you need to use the variable value after incrementing, use i.

The difference between ++i and i++ in js

The difference between i and i in JavaScript

In JavaScript, i and i are two increment operators, used to increase the value of variable i by 1. The main difference is the timing of the increment operation.

i (prefix increment)

  • First increment the value of variable i.
  • Then return the incremented value.

Example:

<code class="javascript">let i = 0;
console.log(++i); // 输出:1</code>

i (suffix increasing)

  • First returns the current value of variable i.
  • Then increment the value of i.

Example:

<code class="javascript">let i = 0;
console.log(i++); // 输出:0
console.log(i);    // 输出:1</code>

Summary

Before increment The value after incrementAfter incrementThe original value before increment
Operator Time to perform increment operation Return value
## i
i

Usage scenarios

    Use # when you want to use the value of
  • i before incrementing it ##i. Use
  • i
  • when you want to use its value after incrementing i.

The above is the detailed content of The difference between ++i and i++ in js. 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
Previous article:How to use || in jsNext article:How to use || in js