alert() is a method of the window object. It is employed to display pop-up boxes with some text and a button labeled “OK”.
Usage of the alert() method is similar to the write() method of the window object. The text placed inside the parenthesis is displayed on the pop-up box.
window.alert("I am an alert box");
Since it’s not necessary to specify the window object we can leave it out from the code. Thus, the following code will function equally well as the one above.
alert("I am an alert box");
When I first came across alert(), I wondered why it is method of the window object and not of the document. The answer lies in the fact that the document object defines only the space in the browser window where an HTML document is displayed. The window object determines the entire browser area including the title bar, status bar, the buttons etc. The alert box pops up because of the browser and not the HTML document. Write() on the other hand specifies what has to be written inside the HTML space and hence is a method of the document object.
There is no difference between the two. Remember, the window object is the highest level object. It can contain other objects and their methods. Hence, document is a object contained inside the window object; write() is a method of the document object and is thus, specified after the document object.
Explicit declaration of the window object is not necessary thus, document.write() works just like window.document.write()
We can’t use the <BR> tag here, as we did in write(), because alert() is a method of the window object that cannot interpret HTML tags. Instead we use the new line escape character.
An escape character consists of a backslash (\) symbol and an alphabet. When preceeded by the backslash, these alphabet assume a special function. Here are some commonly used escapes characters:
(Note: there are other escape sequences that consist of the backslash and hexadecimal digits. Their use is rare … at least I have never used them!)
This looks really messed up. Click here to see the result.
You’ll notice that new lines have been introduced at each occurrence of the \n escape character.
In 1983, Fred Cohen, an American computer scientist, defined a computer virus as a "program that can affect other computer programmers by modifying them in such a away as to include a (possibly evolved) copy of itself". Cohen is known for his research on computer viruses and has developed several techniques for defending against viruses and for automation of protection management functions. [more...]