While syntax: Step 2


#1

This is basic stuff but I still don't understand what's being asked for this seemingly simple intro to While loops:

var understand = true;

while(){
console.log("I'm learning while loops!");
understand = false;
}

I seem to get infinite loops by making the condition TRUE, i.e. 16 % 4 === 0. But then get an error if making it FALSE. I thought I'd want the condition to be TRUE so that the loop converts the 'understand' variable from true to false.

Thanks,

Josh


#3

The while statement requires a condition or state:

while (understand) {

}

fulfills this requirement (understand is a Boolean).


#4

Thank you, mtf. I thought I had to use a mathematical formula that calculates to TRUE.

Best,

Josh


#5

The lesson demonstrates Boolean trueness. From this stems a less specific concept that arises in many situations... truthy and falsy objects.

JavaScript has no declared data types. Variables are said to be loosely typed in that new assignments to the variable need not be of the same type as it was previous. A variable may refer to a number, then a string, then a Boolean, then a reference object (array or object), and so on. The only data type that is excempt of being truthy or falsy is the Boolean type. It consists of only two primitive values: true and false. They require no evaluation. true is true, not truthy. false is false, not falsy.

Everything else, though, falls into one or the other of truthy or falsy, mostly truthy. Let's remove all the falsy values:

0          // zero
''         // the empty string single quotes
""         // the empty string double quotes
null       // a return value that can be set
NaN        // Not a Number
undefined  // a declared variable with no definition

The latter in the list is not one that we can set. It is supplied by the interpreter. When we log a function call expression that has no return value, it will print, undefined:

console.log(console.log("this method has no return value"));
// this method has no return value
// undefined

All other values and objects are truthy. Consider the lesson, in which we set understand to true. We could have set it to any truthy value and it would still yield true in the condition.

var understand = "string";
while (understand) {
    console.log("I am looping!");
    understand = "";
}

Same effect as before. This is an interesting subject so add it to your reading list.

JavaScript data type conversion in condition