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 Basics (Retired) Making Decisions with Conditional Statements Introducing Conditional Statements

Peter Retvari
seal-mask
.a{fill-rule:evenodd;}techdegree
Peter Retvari
Full Stack JavaScript Techdegree Student 8,392 Points

Document.write vs. Prompt method

Hi guys, I have a simple question. Why takes prompt method a higher priority for the browser and display it first even if I write document.write ('Hello World'); in the first line?

1 Answer

Karen Fletcher
Karen Fletcher
19,189 Points

Prompt is a higher "priority" in a way than document.write() because prompt() is used if you want the user to input a value before entering a page. Even if you put document.write() as the first line of your code, prompt() will be rendered first by the javascript compiler engine because actions on the Window take precedence over actions on the document.

This Treehouse Community post from 2016 is along the same lines, and includes "That JavaScript acting on the Window will take precedence over the JavaScript acting on the rendering of the HTML or document object. So the JavaScipt acting on the document will be paused while the JavaScript acting on the Window is still fair game."

references: W3Schools, Treehouse Community post

Steven Parker
Steven Parker
231,269 Points

:warning: that old post contains a good deal of unrelated information and may be confusing.

Also, it's not so much a matter of "priority" or "precedence" as it is a matter of how the browser operates. The JavaScript statements themselves are all executed with the same priority.

The browser doesn't update the page until the program ends. So changes to the page (such as with "document.write) are not visible until then.

This is explained in the "Teacher's Notes" section of the Student Record Solution video.

Karen Fletcher
Karen Fletcher
19,189 Points

@Peter, happy to help!

@Steven, some of the information may be somewhat unrelated, but it also contains a really great discussion that helps provide further context, and shows people talking out a very similar issue and reaching a conclusion together. The teacher's notes you linked is a great concise answer.