0

I have this code;

   function pedirContra(){
            while(contra!="felix123"){
                alert("A");

            }
        }

As you can see, nothing is happening because I have not defined contra. However, if I do so define it using var contra inside the while loop, it will work. Why? Is JavaScript reading the while always, even if the condition doesnt apply? Python always says that the variable doesnt exist.

I tried understanding the code, the only answer I got from myself and my small knowledge, is that JavaScript always reads things even if the conditions dont apply.

  • If you call that function you _will_ get an error: "ReferenceError: contra is not defined". – Andy May 16 '23 at 18:08
  • 1
    `var` declarations are treated as if they appear at the top of the function. – Pointy May 16 '23 at 18:09
  • 2
    Also it's much more helpful to others if the title of your question is something specific about the subject, and not just a generic expression of confusion. Nobody can productively search for the topic of your question. – Pointy May 16 '23 at 18:10
  • @Pointy does this apply to let and const? – Fire Frekox May 16 '23 at 18:10
  • @Pointy Right, will change it. However my english is limited and I dont always have exact titles about things – Fire Frekox May 16 '23 at 18:10
  • No, it does not, `let` and `const` are scoped to the enclosing block (or the loop block in the case of `while` and `for`). – Pointy May 16 '23 at 18:10
  • 4
    [Are variables declared with let or const hoisted?](https://stackoverflow.com/q/31219420) | [What is the difference between "let" and "var"?](https://stackoverflow.com/q/762011) – VLAZ May 16 '23 at 18:10

0 Answers0