24
July

How to: Javascript Globals and Quirks

Welcome to another of my Javascript tutorials. I realised I’ve missed out on a fairly crucial part of the language – the global variables and methods (which are available at all times), and some of the quirks. Lets begin with the quirks.

First quirk is, unlike most C-style languages, you do not need to include a semicolon after each instruction if they are on seperate lines. This means that:

var one = 'test';
var two = 0;
two++;

and:

var one = 'test'
var two = 0
two++

will both run, not throw any exceptions, and result in the variables one and two having the same values.

The second quirk, that follows a little from C and C++, is that any variable can be used as a boolean. For example:

var test = 0;
if(!test){
   // do something
}

will result in the statements within the if block being executed.

These are really the only quirks that are of use in Javascript, so now to move onto the major part of this post – the globals.

The first major global variable is the ‘Window’ object, which contains references to all other global variables and methods, as well as many other useful (and maybe not so useful) variables and methods. It also has a reference to itself.

The second major variable, which you may find you’d use the most for programming in Javascript, is the ‘Document’ object. This object contains methods and variables that help with most things to do with accessing and modifying the DOM.

Another major global is the ‘Location’ object, which allows you to access and change things to do with the current URL. For example, you can redirect users to a new page, or include hash parameters.

The other three global objects are the ‘Navigator’, ‘Screen’, and ‘History’ variables, which provide access to information about the user’s browser, screen and recent history respectfully.

There are four other global variables – Infinity, NaN, undefined, and null. Each one is exactly what you’d think it is, in that Infinity represents any number greater than the largest positive float value, NaN represents a non-legal number, undefined represents an non-defined variable, and null representing a defined variable with no value.

One of the global functions accessible is ‘eval’, which evaluates a string as Javascript code and returns the result. Many Javascript coders try to avoid it’s use, though, as it can do more harm than good if provided malicious code.

Two more functions to help with numbers are ‘parseInt’ and ‘parseFloat’, which parses numbers from a string for you.

Before I start just going on about every method available, I think I’ll just point you all to the w3schools website, which has a complete reference on all standard objects/classes, methods and variables. Next post I will be going into how to create your own classes and objects. Until then, keep coding.
Robert

Leave a Reply

Your email address will not be published. Required fields are marked *

 
%d bloggers like this: