Home > Articles

  • Print
  • + Share This
From the author of

JavaScript Basics

What follows are a small selection of the questions that we have been asked about using JavaScript over the years. These are, we find, the favorite questions—the ones that come up the most often—so we include them here for you to read...hopefully you'll find something new and interesting here!

Why Does Javascript Need to be Enclosed Inside Comment Tags Inside the <script> Tag?

This dates back to when there were JavaScript and non-JavaScript enabled browsers around. The problem was that if a page containing JavaScript was displayed using a non-JavaScript enabled browser, there was a danger of either the script being displayed onscreen, or that an error would occur and the page would look really screwed up. By adding the comment tags, you get over all those problems...but remember to place a JavaScript comment before the last comment tag. Otherwise the JavaScript interpretor will think that they are operators and try to operate with them!

<script language="javascript">
<!--
alert("Welcome to InformIt!");
//-->
<script>

Do You Actually Need to Use the language="javascript" Bit?

It's best that you do. If you leave it out, the browser will use its default scripting language, which might not be JavaScript. Also, by specifying a language attribute, you can customize your script based on the version of the engine, giving you greater control and reducing the problems of writing for more than one browser.

Where Do I Place the <script> Block?

It can go pretty much anywhere in the HTML of the page, but if you stick with it in the <head> for as much of the time as possible, you'll make your life easier because that way you guarantee that your script will be loaded before the page, and reduce errors.

What Kinds of Errors?

Take rollovers on a page. If you allow the page to load in before the script, users will get error messages when they roll over the hot image—which looks really bad and is really annoying!

Do I Really Need those Semicolons (;) at the End of Each JavaScript Statement?

You only really need those semicolons if you are stringing more than one statement on the same line; something like this (in which we have statements within event-handling attributes as part of a string):

<a href="http://www.kingsley-hughes.com/index.htm" 
  onMouseOver="window.status='Click to visit our website!!!'; return true;"
  onMouseOut ="window.status=''; return true;">Click Here!</a>

Adding the semicolons at the ends of statements does make your code a lot more readable and easier to follow, so they might be worth adding. However, if you want less to type, just leave them out!

Help, I'm Having Problems Using Quotations in My Code!

When you want to use quotations, or in fact any other character that you are having problems with, you can prefix them with the backslash (\) character:

\b Backspace
\f Form feed
\n Line feed (newline)
\r Carriage return
\t Horizontal tab (Ctrl-I)
\' Single quotation mark
\" Double quotation mark
\\ Backslash

How Do You Get a Carriage Return in a Dialog Box?

Use \r at the point where you want the return.

What About On the Page, as When Using a document.write()?

In this case, you need to forget the \r and go with the HTML <br>.

My JavaScript Math is Wrong! What's Up with It?

This isn't really anything to do with accuracy, only with the way that JavaScript does the math internally. In most cases, you can avoid any unexpected results by rounding the result of your calculations to the precision of the most precise number in your equation. So, if you have the following, this can come out as 11.899999, instead of 11.9:

0.119 * 100 

To get the correct answer, you would need to round the output to three decimal places.

Can I Hide My Script from Prying Eyes?

Only if you want it to work in Internet Explorer! Microsoft has bought out a script encode that will encrypt your script yet still allow it to work.

Get the script encoder from: http://msdn.microsoft.com/scripting/vbscript/download/vbsdown.htm.

How Do I Round Numbers Off to a Certain Number of Decimal Places?

Use Math.round() to multiply the number by ten times the number of decimal places you want to round off by; then divide by that number.

For example, this will round off to tenths:

var pi = "3.1415926535";
pi = Math.round(pi*10)/10;

And this to hundredths:

pi = Math.round(pi*100)/100;

Can I Take My Javascript Code Out of the HTML and Put It In a Separate File?

Yes. Create a new file with the extension .js—for example, script.js. Put your JavaScript code in this file.

NOTE

You do not include opening and closing <script> tags in the .js file!

To embed script.js into your Web page, use these tags in your HTML file:

<script language="JavaScript" src="script.js">
</script>

NOTE

Some older browsers (such as Navigator 2.x and Explorer 3.x) cannot make use of external JavaScript files.

What Reserved Words (Words that You Cannot Use) Does JavaScript Have?

Here are the reserved words for JavaScript. When choosing names for your JavaScript variables, avoid these reserved words.

abstract else instanceof switch
boolean enum int synchronized
break export interface this
byte extends long throw
case false native throws
catch final new transient
char finally null true
class float package try
const for private typeof
continue function protected var
debugger goto public void
default if return volatile
delete implements short while
do import static with
double in super

In addition to the previous list, here are other words you should avoid (they are the names of client-side objects, methods, or properties in Netscape Navigator or Internet Explorer):

alert hidden outerWidth
all history packages
anchor image pageXOffset
anchors images pageYOffset
area isNaN parent
array java parseFloat
assign JavaArray parseInt
blur JavaClass password
button JavaObject pkcs11
checkbox JavaPackage plugin
clearTimeout innerHeight prompt
clientInformation innerWidth prototype
close layer radio
closed layers reset
confirm length screenX
crypto link screenY
date location scroll
defaultStatus Math secure
document mimeTypes select
element name self
elements navigate setTimeout
embed navigator status
embeds netscape String
escape Number submit
eval Object sun
event offscreenBuffering taint
fileUpload onblur text
focus onerror textarea
form onfocus top
forms onload toString
frame onunload unescape
frames open untaint
frameRate opener valueOf
function option window
getClass outerHeight

NOTE

Some of these words are actually part of the Java language, and are reserved in JavaScript for compatibility purposes.

How Can I Generate Random (or Pseudorandom) Numbers in JavaScript?

To generate random floating-point numbers in the range from 0 to 1, use the Math.random() method:

num = Math.random() 

If you need random floating-point numbers in the range from X to Y, use this code:

num = X + (Y-X)*Math.random()

I'm Worried About "Millennium Bugs" In My Code. What Can I Do?

You can use the following code snippet to correct any problems you might come across when retrieving the current year:

theDate = new Date();
theYear = theDate.getYear();
if (theYear<1900) theYear=theYear+1900;
  • + Share This
  • 🔖 Save To Your Account