Learning javascript. The textbook says:

i ++; // shorter record for i = i + 1

A shorter entry, as I understand it, is done for the following:

optimize (shorten) the code and make it clearer; it is logical that the shorter is equal to the full.

But I ran into a simple example (in the future we will call it Example # 1 ):

i = 0; while (i++ < 5) { alert(i); } 

And I decided to write it down, in an abbreviated form (after all, they are equal). I could not get:

 i = 0; while ((i = i + 1) < 5) { alert(i); } 

Because of the parentheses, the priority changes (with the five, the comparison is already after +1) and the last alert produces a four. It is surprising that I can not make a complete record, where made abbreviated.

  • I want to get the result, as in Example # 1 , but at the same time make a record not abbreviated, but full (i.e. (i = i + 1) )
  • The postfix form and the prefix form, I know about them, they do not play a role here in my opinion. If this seems important to you, use them in your explanation.
  • This option:

 i = 0; while (i < 5) { i = i + 1; alert(i); } 

I also do not like it, it is necessary that the complete entry be in parentheses of the while, as well as abbreviated.

My question is:

Explain to me how it works. ! It is necessary to use a while loop as in my example, if the records are equal, you will have no difficulty writing it down. It is advisable that your explanation be reduced to the following:

  1. i++; // более короткая запись для i = i + 1 i++; // более короткая запись для i = i + 1 This is not true, entries are not equal and ...
  2. i++; // более короткая запись для i = i + 1 i++; // более короткая запись для i = i + 1 Records are equal and your code (we read what result I want to get above) ...

PS This is not a duplicate question, I write because another user ru.stackoverflow, marked the question "as a possible duplicate." This question is well decorated and clearly stated, detailed answers were given. If in this question you find something familiar and close, it does not mean that it becomes a duplicate. It is better to read the question again, read and comment on it, rather than write a link to a topic that has already been raised here several times. This question reflects the desire to understand, it is understandable and is beneficial (the author certainly).

  • one
    My question is completely about another vp_arth, which duplicate? - Alexander Kazakov
  • 3
    For my taste, ++i (I hope in JS also has such a record) closer to i = i + 1 . / Author, one little tip for the future. At first, once you read the topic completely and only then (preferably, even after a little thought), you are taken for exercises. - avp
  • one
    @Other, what is the assignment in question? And the behavior of while (++i < 5) and while ((i = i + 1) < 5) (at least in C) is the same (the cycle is executed 4 times), and both differ from while (i++ < 5) ( 5 times) - avp
  • 2
    Possible duplicate question: What is a post-increment and pre-increment? - ߊߚߤߘ
  • one
    I do not agree that the duplicate, the question is wider and affects a new problem - Crantisz

3 answers 3

In this case, there is a misinterpretation of what is written in the textbook.

 i++; // более короткая запись для i = i + 1 

Pay attention to ; in this entry.

Indeed string

 i++; 

can be painlessly replaced by

 i = i + 1; 

The postincrement feature is that this operator returns the value before the increase. And, since the line i++; This value is not used anywhere; the above entries are equivalent.


If the return value is used, as in the case in the question, then the answer @good_web_master clearly demonstrates the equivalent expressions:

 a=i++ => a=i i=i+1 

As you can see, in order to fully emulate a short record, you need to save the value somewhere before increasing, it can be:

  1. third-party variable

     var i = 0, a; while ((a = i, i = i + 1, a) < 5) { console.log(i); } 

    In this case, the operator Comma ( , ) allows you to return the value of a for comparison in the condition.

  2. directly created structures:

    1. an object

       var i = 0; while ({pred:i, curr: i = i + 1}.pred < 5) { console.log(i); } 

    2. either array

       var i = 0; while ([i, i = i + 1][0] < 5) { console.log(i); } 

  • 2
    A lot of extra letters. - user207618
  • Add my options from the comment. About <=5 at least. - vp_arth
  • one
    @vp_arth, better add your answer - Grundy

"they do not play a role here" - just play:

i++ - returns the value to increment, a

i = i + 1 - after.

 var i = 0; // здесь с единицей сравнивается значение i до инкремента - то есть 0 if (i++ < 1) { console.log("i - check " + i); } var j = 0; // здесь с единицей сравнивается значение j после инкремента - то есть 1 if ((j = j + 1) < 1) { } else { console.log("j - no check " + j); } // однако: var k = 0; // здесь с единицей сравнивается значение k после инкремента - то есть 1 if (++k < 1) { } else { console.log("k - no check " + k); } 

typing a while in the light of acquired knowledge is left to the author of the question as an exercise

  • Comments are not intended for extended discussion; conversation moved to chat . - Nicolas Chabanovsky
  • @AlexandrKazakov, the cons are not removed, except, perhaps, exceptional measures. - user207618
  • @Other Let's not get tired, and we will vote a person for the question. I have already. - Igor
  • Where are your principles, Baronet? - user207618
  • @Other I do not waste their bank! - Igor
 var i = 2; i++; // более короткая запись для i = i + 1. alert(i); // 3 

It is in this form, not as an expression, that this is a shorter record, because it does exactly the same thing - it increases the value of the variable i by one.

What is the difference?
In return value.
The i++ expression returns the value of the variable i before incrementing.
The expression (i=i+1) (like ++i ) returns the value of the variable i after increment.

There are many ways to bring the second expression to the first, for example:

  • Save original value: (temp = i, i = i + 1, temp)
  • Calculate the initial value: (i = i + 1) - 1

 { // Вариант с сохранением значения let i = 0, temp; while (temp = i, i = i + 1, temp < 5) console.log(i); } { // Вариант с восстановлением значения let i = 0; while ((i = i + 1) - 1 < 5) console.log(i); } // Можно также произвести некоторые математические операции для упрощения { // Увеличим обе части неравенства на 1 let i = 0; while ((i = i + 1) < 6) console.log(i); } { // За счёт нестрогого неравенства можно сохранить первоначальную константу let i = 0; while ((i = i + 1) <= 5) console.log(i); }