Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops A Closer Look at Loop Conditions

Aaron Munoz
Aaron Munoz
11,177 Points

Prompt(); runs within a variable?

How come the promp(); function runs automatically even if it's not called simply by storing it in a variable?

For the exercise I wrote this code and it worked perfectly but don't understand why if the variable secret was never called:

var secret = prompt("What is the secret password?");

while (secret !== "sesame") {
  secret = prompt("What is the secret password?");
}

document.write("You know the secret password. Welcome.");

3 Answers

Its because it's a window modal Method, not a function. Basically the prompt method is executed when the JS reads the window element. The same thing with alerts and confirms. If you like here is an interesting post about it.

the prompt() method's full syntax is:

window.prompt(param);

www.developer.mozilla.org/en-US/docs/Web/API/Window/prompt

what do you mean by this:

why if the variable secret was never called:

EDIT

The prompt will execute without it being called like a normal function because it's a method on the object window. the prompt will then return a string if entered into the box and then the string will be assigned to that variable.

and yes, a method is a function. it's just a function on an object.

Aaron Munoz
Aaron Munoz
11,177 Points

That link is broken. But I see what you're saying. If it was any other method not built that way, the variable would have to called.

jason chan
jason chan
31,009 Points

because prompt(); is a function.

When it's called it' will store in var

Then you make the var do something if and then statement.

Aaron Munoz
Aaron Munoz
11,177 Points

Well, in this case prompt runs and pops up a window first and then stores the user input.