First steps in JavaScript

Printing values

Since JavaScript manipulates web pages, there is no print statement provided to instruct the computer to print a value to the screen. This leaves a few options for a beginning programmer, with various advantages and disadvantages, depending on what gets changed and how.

One option uses the console, which is a special display of information that can be viewed on request, but as a default is hidden from users of the page. This is typically used for debuggingThe process of removing errors from code. by developers, as error messages can be displayed there.

Option Result Cautions
alert("message") Creates a new window containing the message. Click in the window to dismiss it.
document.write("message") Writes the message on the page. Previous page contents are replaced.
console.log("message") Prints the message in the console. Make sure you can see the console.

As you might imagine, using alert can quickly get very annoying, as it takes over control of your machine until you dismiss the window. Using document.write can be quite dangerous, as you might inadvertently lose information that was on the page.

Until we learn how to use the Document Object Model to modify pages, we will mainly use console.log. You don't need to worry about how to make the console visible, as we will provide consoles as needed in examples and exercises. For work outside the course, the Help page gives information on how to view a console in a browser.

Documentation, testing, and programming style

Due to the space limitations in examples and the assumption made about programming background, most of the examples do not include adequate documentation, nor is there discussion of good programming style or testing. You might wish to watch our videos on good programming practices for coverage of such topics. You might also wish to come up with your own exercises to obtain more practice in using JavaScript.

On the topic of documentation, when writing commentsInformation written for humans, ignored by the computer. to be read by humans but ignored by the computer, make use of // to show that the rest of the line is a comment, and use /* and */ for a comment that extends over one or more full lines. This example makes use of both ways of showing comments:

/* A multi-line comment can go on and on and on 
   and on and on if you really want.
*/
console.log(":)"); // Insert comment about emoticons here.