10/11 Can anyone explain this


Can anyone please explain to me how this code is run in javascript? Why do I put x= false in the 'do' section versus why can't I put it in the 'while' section or even just as a part of the function?

var getToDaChoppa = function(){

var x = true;
do {console.log("This is the 'do' part");
x = false;
} while (x === true);




Ok so first of Hello there @goldiefish! Lets get to the topic! So first your making a function called getToDaChoppa Here:

Secondly the reason you cant put a while part is beacause the diffrence of a do-while and a while is that in a do-while you run it THEN you check for conditons so it has to run at least once. But for while you check THEN run it so there is a possibilty it can never run. So back to the code

You set var x to true then you do the part:

AND THEN set the x to false.

Then when it goes to the while statement it says

And x isnt true so it wont Do it the second time. Understand now? Here is a better explanation if you need it


@ amanuel2 thanks so much! It also seems like 'var' is very important part of this. first we assign 'var' is true and then we change that to false and since javascript only looks at the last assigned variable value, this may be why this works.


var does basically just means "give me some space for my variable here". So it is a keyword that should be used when introducing a new variable. As you in this case overwrite the value directly afterwards you might as well assign a value in the first place:

var x;
do {
    console.log("This is the 'do' part");
    x = false;
} while (x === true);


how come in the beginning of your code, you only put var x without giving it a value? shouldn't that not work?



Var x; is like saying Var x = null; Its equal to nothing. But then in the do statement as @haxor789 does he changes the value of Var x = null; to Var x = false; . null means nothing. Here is a clear explanation of it.


Ah! That makes total sense. Thank you very much!


Just using var x means give me a variable named x. It is so called declared but it is not defined meaning you did not assign a value to it and thereby defined a type. So the essence of what @amanuel2 said is correct just that the value is undefined and not null as you can see:

var x;
console.log(x === undefined); --> true

Still the idea is you declare it empty and later give it a value.