Categories:

The typeof operator

The "typeof" operator in JavaScript allows you to probe the data type of its operand, such as whether a variable is string, numeric, or even undefined. The below simple example alerts the data type of the variable "myvar"

var myvar=5
alert(typeof myvar) //alerts "number"

Here's a list of possible values returned by the typeof operator:

Evaluates to Indicates
"number" Operand is a number
"string" Operand is a string
"boolean" Operand is a Boolean
"object" Operand is an object
null Operand is null.
"undefined" Operand is not defined.

So, it doesn't take a rocket scientist to figure out now how to detect whether a variable is defined (exists) in the script:

if (typeof x=="undefined")
	alert("Variable x doesn't exist)
else
	// continue with script

Ok, now that you know, why should you know? Well, the ability to find out whether a particular variable is defined or not is not only useful, but essential, in some scripting scenarios.

Allow me to present an example. Let's say you're writing a function that loads any URL into the same secondary window. As easy as this task may seem, it actually is not- unless you know what you know!

The basic function for opening a new window and loading any URL into it looks something like this:

function openfile(url){
	win2=window.open(url)
}

With the above function, a new window is opened each time it is called. What you want (ok, what I asked for) is a function that will only open one new window regardless of how many times the function is called. Once this single new window has been opened, calling the function again should load the URL into this window, not annoy the heck out of visitors by spawning a new one each time. In order to accomplish this, we need a way to determine whether the designated secondary window (win2) is opened already or not, and only open another window if not. How are we going to do that? Take a look at the modified function below:

function openfile(url){
	//if "win2" doesn't exist or has been closed closed
	if (typeof win2=="undefined" || win2.closed)
		win2=window.open(url)
	else //else if window already exists, just load URL into it
		win2.location=url

The above function does exactly what the requirements call for...it opens up a set new window, and loads the specified URL into it. You can call the function as many times as you wish, and only one new window is opened. Without the knowledge we've learned in this tutorial, this simply wouldn't have been possible.

It's hard for me to tell you exactly when and how you'll need to determine whether a variable exists or not, but believe me, it will definitely come in handy in the future (if not already) as you script away and build more and more complex scripts.