About The JavaScript Examples

Recently I've been asked a few times why I used the document.write() function to display values in many of the JavaScript examples. The questionner usually points out that document.write() is regarded as unsafe because when it is called once a web page is fully loaded, it overwrites the current document. While this is correct, it doesn't apply to any of the examples in this book - let me explain.

When teaching programming it's necessary to have a quick and easy way to display the results of expressions. In PHP (for example) there are the echo and print statements, which simply send text to the browser, so that's easy. In JavaScript, though, there are these alternatives:

What's more, document.write() is a single, short function call that is self-evident as to what it does, and is therefore perfect for quickly displaying a result. It keeps all the examples short and sweet, and places the output right there in the browser. As many programmers agree, document.write() is useful for testing short code snippets, and for for displaying quick results. And, following correct practice, none of the examples in this book that continue to run after a page has fully loaded, use the document.write() function - other, better methods are always taught and employed.

In summary, document.write() is only ever used in this book as a convenience (instead of calling the console.log() function) to show values or the results of expressions. It is never used to (or intended to teach how to) display web browser content.

I hope that clears things up, and thanks for asking :)