6/11


#1
//Remember to make your condition true outside the loop!
var bool = true
var soloLoop = function(){
  //Your code goes here!
  while(bool) {
      console.log("Looped once!");
      var bool = false;
  }
};

soloLoop();

This is the code I have, I keep getting asked "Did you log 'Looped once!' to the console?"
I'm not sure what's wrong with it.


#2

Hi @stevew1113

You have to delete the keyword "var" before bool in your while loop.


#3

Just FYI what you see here is a good example for shadowing and hoisting. Shadowing is something you could have seen in the function track, it is when you declare a variable inside a function which has the name of a variable outside of it. So in your case bool. By declaring bool inside of the function you create 2 variables with the name bool one that only exists in the function and one outside. They share nothing but the name and the variable outside of the function is not accessible from inside the function not because it is not global, but because the name is already taken that's why it is called shadowing.

So back to your code you could add a console.log(bool) to see:

var bool = true
var soloLoop = function(){
  //Your code goes here!
  console.log("value of bool: "+bool);
  while(bool) {
      console.log("Looped once!");
      var bool = false;
  }
};

soloLoop();

that the value of bool inside of the function is undefined and not true. And the effect that the var bool is used although it comes later in the function as the console.log is called hoisting. So any variable declaration is hoisted to the top of the function.

And you can easily solve it as @onepunch_man said by deleting the var keyword. Hope this was not too boring or confusing.


#4

I like the @haxor789 's explanation :+1: