|
-
October 24th, 2001, 08:37 AM
#1
JavaScript: how to know if a variable is defined ?
Hello,
Is there a way to detect in JavaScript if a variable has been declared or not ?
Thanks,
Jerome
-
October 24th, 2001, 01:31 PM
#2
Re: JavaScript: how to know if a variable is defined ?
Here’s a sample that shows how to use the typeof operator to determine a variable’s type.
<html>
<head>
<script language="javascript">
function test()
{
var a;
alert("The next pop-up displays the sample code,\n the ones following that display the result");
alert(test);
a="hello";
alert("typeof(a) = " + typeof(a));
alert("typeof(b) = " + typeof(b));
}
</script>
</head>
<body background="images/bg_light_gc.gif">
<input type=button onclick='test()' value="Test">
</body>
</html>
Paste the code into an HTML file, open the file using a browser, and click the button to see the result. The first thing the code does is show you the code for the test function, it then shows the types of variables a and b - only variable a is declared and defined.
Unfortunately you cannot determine if a variable has simply been declared using the same approach because all JavaScript variables start life as undefined objects, even if they have been declared. JavaScript variables work like this because declaring variables is completely optional in JavaScript, meaning that you can introduce a new variable at any time and have JavaScript use it right away.
Essam Ahmed
___________________________________________________
Author of JScript .NET Programming - Now Avaialble!
http://www.designs2solutions.com/jsnetprg
See how easy it is to:
o migrate from ASP to ASP .NET
o create a Web Service
o consume a Web Service from a Windows Forms app
o work with ADO .NET
o work with ADO in an ASP .NET application
o migrate from ADO to ADO .NET
o ...and more!
o Accepting subscriptions for a newsletter on the .NET Framework and JScript .NET - Subscribe Today!
http://www.designs2solutions.com/jsnetprg
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|