Why this do-while print out 2 times


#1



i = 19;
do {
    console.log(i);
    i++;
} while(i < 20);


5. How to get it to print the actual result
#2

Do-While loops run the code once before checking the conditions, before running the code again, and so on. It only logs once, but returns once as well, because that's how the Codecademy console works - don't ask me - I don't know :stuck_out_tongue:
You can test it like this:

var i = 19;
do {
    console.log(i + " blah"); //Will log '19 blah'
    i++;
} while(i < 20); //Will not run again

So it will log "19 blah" once, then return 19 because that was the last value for i, and that's the way the console here works.

If you have any more questions, feel free to ask! :slight_smile:


Introduction to 'While' Loops in JS - Do / while loop doesn't print text string on final loop
Why does my code return the entire structure of Steve twice and Bill once?
Contact List Returning Multiple Keys From The Two Names Even Though the Program Only Instructs for One
Why is the console printing the number 3 after running my code?
#3

As your code, the Coadcademy output screen shows:
19 blah
19

I don't understand why this web's console show the last value of i, but thank you for your explaination


#4

@athithan.ruagmail.co,
++++ why second display of last Item
+++++++++++++++++++++++++++++
It is the Javascript interpreter which is running in this course-environment,
it display's the last non-displayed action...

You will also encounter this, when you are doing a return-statement
as last action...
You could counter this by using a
console.log( " " ); as last statement....

In some sections of this course, the course-checker Display's data
this you could then identify by placing two EXTRA code-line's:
console.log( "== My End ==" );
console.log( "== All that is displayed now, is the course-checker ==" );


#5

@jibblyj, is that why I have a 1 at the end of my do while console logs but not at the end of my for and while loop ones? I want to make sure I'm understanding you correctly.

Thank you,
frisby


code:

for (var i = 0; i < 3; i++) {
    console.log("Yo mama " + i);
}

while (i < 6) {
    console.log("Yo mama " + i);
    i++;
}

do {
    console.log("Yo mama " + i);
    i--;
} while (i > 0);

Console reads:

Yo mama 0
Yo mama 1
Yo mama 2
Yo mama 3
Yo mama 4
Yo mama 5
Yo mama 6
Yo mama 5
Yo mama 4
Yo mama 3
Yo mama 2
Yo mama 1
1


#6

Yes.   


#7

Not just the CC console, that works for any web console I've tested. When you enter a value in the console you get the value echoed back. Meaning you could use it as a calculator:

input: 2+2
output: 4

If you write a longer program it just echoes the last value. An exception is undefined, so when you use e.g. console.log, as Leon suggested, you won't see such an output.

In general it is a nice feature to see if you're code gives the correct output without a console.log but I wouldn't rely on it, as it only works for the last value and test functions might not recognize it, as console.log triggers a different channel than this echo feature.

And in case someone asks why it is 19 and 1 although the value of i should be 20 and 0 after finishing the code.
Well the explanation that i++ and i-- are a synonym of i=i+1 and i=i-1 is only partially true.
Yes the effect on i is the same, but the value is different. For example statements like name = VALUE have a value of VALUE e.g.

console.log(answer = 42); --> 42

But e.g. i++ has a value of i but an effect of increasing i by 1. If you really want the same effect and value you could use ++i or --i or i+=1, i-=1.


Lesson 6:is my code correct?
Search for a friend; One Bill, Two Steve
#8

Great; thank you for the explanation and confirmation, jibblyj!


#9

And in case someone asks why it is 19 and 1 although the value of i should be 20 and 0 after finishing the code.
Well the explanation that i++ and i-- are a synonym of i=i+1 and i=i-1 is only partially true.
Yes the effect on i is the same, but the value is different. For example statements like name = VALUE have a value of VALUE e.g.

That "someone" is me exactly :joy: @haxor789

I've thought about this for a while, read about it on stackoverflow, and asked someone about it irl, but am still confused 11 days later.

I mean, I understand that i++ returns the value i and then increments. Or is it not returning?

  • I would guess that it returns because A, the console shows the last value returned (19) and B, I've only seen it described in this way. But on the other hand if it returns, wouldn't the rest of the function not execute?
  • In which case I wonder how does the program know to continue with the ++ part of the operation?
  • And then my question becomes if i++ returns 1 and then ++, if i + 1 (or 20) is now the new value of i, why wouldn't the console show 20? (In which case I'd guess the answer is linked to my first question regarding the last value returned and..my mind goes in a circle like that.)

Yes the effect on i is the same, but the value is different. For example statements like name = VALUE have a value of VALUE e.g.

console.log(answer = 42); --> 42

To be sure I understand that name is VALUE and i is i, not i + 1, but then how does the program(???) keep track of the new value becoming i + 1, i.e. if I console.log(i) under i++ why does it print i + 1 and not i?


#10

@msfrisby,
Look at the diff
using

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

and did you come across this article
http://stackoverflow.com/questions/971312/why-avoid-increment-and-decrement-operators-in-javascript


#11

Thank you for your help, @leonhard.wettengmx.n!

I did not see that article before but I read it now. I especially found this answer helpful:

It is simple enough. value++, give me the current value and after the expression add one to it, ++value, increment the value before giving me it. *emphasis mine

var a = 1, b = 1, c;
c = a ++ + ++ b;
// c = 1 + 2 = 3; 
// a = 2 (equals two after the expression is finished);
// b = 2;

although based on another answer lower on the page it sounds like c should be a++ + ++b and not as written with spaces

I read about post and pre-fix when I saw haxor's post and thus used ++i instead of i++ for the remainder of the course, but before reading this I think I definitely would have given the wrong answer to c. :cold_sweat:

I also ran your programs and the output was as I expected (=>4), while switching the order the output was also as I expected (=>5). However, I still don't understand why the first way the final value is 4 and the second way the final value is 5?


#12

@msfrisby,
You are actually on the hunt for an assembler code kind of explanation....

It seems they use 2 separate CPU Registers
1 for the condition-block
1 for the code-block

You will see the Register =>Value of the code-block

If you use i++ your condition-block is updated,
and if condition is pass-thrue
then the code-block Register is updated by picking the new-Value

If you use i+=1 both the condition-block and the code-block Registers are updated

Try by removing the =comment-indicators=

console.log("=increment in loop def=");
for (var i=0 ; i<5 ;i++){
   //code-block
   //console.log(i)
   //i++;
}

/*
console.log("=increment in code-block def using ++ =");
for (var i=0 ; i<5 ;){
   //code-block
   //console.log(i)
   i++;
}

///*
console.log("=increment in code-block def using +=1 =");
for (var i=0 ; i<5 ;){
   //code-block
   //console.log(i)
   i+=1;
}
*/

#13

Thank you so much for your reply, @leonhard.wettengmx.n! I think I am beginning to understand. :nerd:

So in the i++ program, when i = 4, after the i++ is the condition block updated to i = 5 while the code block is not, or vice versa? Or are they both updated?

And if I edit the i++ program like so:

console.log("=increment in code-block def using ++ =");
for (var i=0 ; i<5 ;){
  //code-block
  console.log(i);
  i++;
  console.log(i); // <--here
}

What his happening in the second console.log? Why does it print the new i value?


#14

@msfrisby,
Because the console.log() will FETCH the new i-Value
to use it in its excution/code-block Register


#15

Thank you for your answer, @leonhard.wettengmx.n. This made me realize I thought I was confused about the code block part, when I was actually confused about the code block to condition block part. I've thought about it again...

So the difference between for (var i = 0; i < 5; ) and for (var i = 0; i < 5; i++) is that in the first one, the value of i is updated both in the code block and in the conditional block (on the last loop, both know i = 5), while in the second one, only the conditional block knows i to be 5 while the code block thinks it is 4?

The conditional block knows everything the code block knows but the code block only knows what the conditional knew the last time the code block ran?

A further bit of confusion: Rethinking this, I ran again your two programs, this time next to these two:

for (var i=0 ; i<5 ; i++){
   //code-block
   console.log(i)
}

console.log("=increment in code-block def using +=1 =");
for (var i=0 ; i<5 ; i+=1){
   //code-block
   console.log(i)
}

And I also edited your += program to this:

console.log("=increment in code-block def using +=1 =");
for (var i=0 ; i<5 ;){
   //code-block
   console.log(i)
   i+=1;
   console.log(i)
}

And now I'm a bit more confused. (Maybe I just took a step backwards and am momentarily disoriented?) I expected the outputs of the ++ programs to be different from the += but they are the same?

When I look at the programs in isolation I think I wasn't surprised the outputs are the same, but when I compare them to the while programs which were different...in that context I don't understand why these are the same and am confused...


#16

@msfrisby
Do NOT use console.log()'s !!!!!
the actual-i-Value will then be in the execution/code-block Register AND an output has been done
and you will not have the ==> .Value


#17

@leonhard.wettengmx.n Oops, sorry! When I ran your original programs too I thought I was supposed to uncomment the console.logs. I still did see the ==> value; I'm guessing the key difference is that the incrementer came last?

However, I am still confused about the points I was confused about before I tried adding the console.logs (conditional block vs code block incrementation).


#18

Well you need to distinguish between the value of an expression an the value of a variable. As said the value of the expression:

A = B

would be B, as a side effect A would after the execution of this statement have a value of B as well, but you could just use A = B as alias for the value B.
Now from what they are doing:

i++
++i
i+=1
i=i+1

are all the same, all of them increase the value stored in the variable i by 1. The difference is that these expression itself have values.

    i++

has a value of i.

    ++i

has a value of i+1.

    i+=1

is just a shorthand version of:

   i=i+1

which has as said a value of i+1, because here you first compute the value of i+1 and the you have the regular A = B assignment that has a value of B.

WARNING!!!
THE FOLLOWING IS ALMOST CERTAINLY NOT HOW IT WORKS!
An intuition might be:

    //prefix incrementation
    var ++a = function(a){
        var result = a+1
        a = a+1
        return result
    }
    
    //postfix incrementation
    var a++ = function(a){
        var result = a
        a = a+1
        return result
    }

What you see in the console is therefore the value of the expression and not necessarily the value of the variables itself. What magic occurs when the increment is used in the for loop goes beyond my knowledge as I do not know how the particular JS implementation runs the code internally. Normally programming languages define a framework what they expect to happen for certain commands (standard) and those who implement it just make sure that this is happening. Also avoid extensive usage of this side effects as possible because there are many ways to use the + sign:

string concatenation
sign like in -1 and +2
addition
increment operator ++ --

and depending on where you set the spaces a + +b could be valid whereas a++b is an error as neither a++ b nor a ++b makes much sense and so on.


#19

Thank you so much for your answer, @haxor789!

Before this I hadn't heard of "alias" so I looked it up ("aliasing refers to the situation where the same memory location can be accessed using different names"). In context of

A = B as alias for the value B

  • does this mean (A = B) => B, A = (B=B), or maybe does it not matter because of the transitive property or something?

I appreciate the "intuition" explanation, it really helped clear up my confusion.

  • Am I understanding correctly that "intuition" means I can think of it as working this way, but that is not necessarily so?

What you see in the console is therefore the value of the expression and not necessarily the value of the variables itself.

This was also really helpful to hear, especially in conjunction with your expression-value breakdown. I realise now I'd been conflating understanding the difference between pre and postfix with understanding JS's internal implementation...

Finally, if I may ask, what side effect are you referring to here:

Also avoid extensive usage of this side effects as possible because there are many ways to use the + sign:

  • Is the suggestion to avoid use of the ++ operator when possible?
  • Do you know of a good reference for the explanation of "side effects"? I read about it in Eloquent JS and on stackoverflow but there seem to be many conflicting definitions.

#20

Ok sry, I just meant alias as "another name for" meaning that both B and A=B or ANYTHING = B have the same value of B. That is probably what the programing term means as well but I'm not 100% sure how javaScript handles it's memory management as it is a high level language without access to the "real memory". But I've run a test with an object:

    test = {test:"test"};
    A = B = test
    test.test2 = "test2";
    console.log(A);
    console.log(B);

And both console.logs show the altered version of test meaning that you probably have a real reference to a point in the memory instead of just a copy. But that is definitely beyond the scope of this exercise :slight_smile: and the beauty of high level languages is that you do not have to deal with memory management that much.

yes it is meant to illustrate the difference between the value of the expression and the value of the variable but as variables in js must not start with an ++ this is obviously not how it is done but if you would replace every i++ in your code with increment(i) resembling the intuition function you might have a similar effect.

For side effects I'd just refer to the wikipedia on side effects. And no using ++ operators in loops or alone is fine but doing stuff like this:

c = a ++ + ++ b;

would be something I'd like to avoid as it is even hard to read what is happening and it might as said behave differently when spaces are replaced.