Search this site...

Sending output to a web page

JavaScript provide two methods for displaying text on a web page:

  1. document.write ("SomeText");
  2. document.writeln ("SomeText");

Note we used a semicolon above in each of the two statements. Any JavaScript statement (a complete JavaScript command) must end with a semicolon to mark the end of the statement.

If you have worked with a object-oriented language, you will immediately recognize that document is an object and both write and writeln are methods. The term "method" in context of object-oriented language means an action. As noted earlier, both of these actions print text. But what text do they print? Any text that is enclosed inside the double quotation marks ("") or single quotation mark ('').

So the next question you may want to ask is what is the difference between these two methods? The "write" method prints the text to the browser without attaching a carriage return at the end of the text while the "writeln" method adds a carriage return to the end of text that you want to print to a web page.

Consider the following example that uses the "write" method

<script language="javascript">
document.write ("<pre>Line 1");
document.write ("Line 2</pre>");

to print the following:

<script language="javascript">
document.writeln ("<pre>Line 1");
document.writeln ("Line 2</pre>");

The output

however is different if we use the "writeln" method:

We used the <pre> tag to show you the difference between the two methods. The "writeln" method, again, prints text with a carriage return at the end of the line. To show you that affect, we have to use the <pre> tag.

You can also use HTML tags to format text inside the write or writeln method. For instance,

<script language="javascript">
document.write ("Learn JavaScript from the <b>Scripting Master!</b>");

will print:

Recall that the <b> tag in HTML is used for making some text bold.