Output (writeln) & Output (alert) in JavaScript

Output-(writeln)-&-Output-(alert)-in-JavaScript

Output (writeln)

One of the most important things to do when learning a new language is to master basic input and output which is why hello world has become almost a cliché  in programming textbooks. For Javascript you need three hello worlds because there are three ways to communicate with the user, each increasingly more useful than the last.

The first method is to use the document.writeln(string) command. This can be used while the page is being constructed. After the page has finished loading a new document.writeln(string) command will delete the page in most browsers, so use this only while the page is loading. Here's how a simple web-page will look... 

 <html>
  <head>
  </head>
  <body>
     <script type='text/javascript'>
        document.writeln('Hello World!');   
     </script>
  </body>
</html>

As the page is loading, Javascript will encounter this script and it will output "Hello World!" exactly where the script block appears on the page.

The problem with writeln is that if you use this method after the page has loaded the browser will destroy the page and start constructing a new one.

For the most part, document.writeln is useful only when teaching yourself the language. Dynamic content during page load is better served by the server-side scripting languages. That said, document.writeln is very useful in pre-processing forms before they're sent to the server -- you can basically create a new web-page on the fly without the need to contact the server.



Output (alert)

The second method is to use a browser alert box. While these are incredibly useful for debugging (and learning the language), they are a horrible way to communicate with the user. 


Alert boxes will stop your scripts from running until the user clicks the OK button, and it has all the charm and grace of all those pop-up windows everyone spent so many years trying to get rid of!

<html>
  <head>
  </head>
  <body>
     <script type='text/javascript'>
        alert('Hello World!');
     </script>
  </body>
</html>

Comments

Popular posts from this blog

How to Connect Android to Multiple WiFi Hotspots

Free URL Submission in Search Engines and Web Directories

Connectify Dispatch & Hotspot Pro v4.0 (Full & Free Download)