Hey Folks,
Anyone know how to test for the existance of a variable in javascript?
I'm looking for the equivalent of IsSet() from PHP. I'm having trouble
finding it.
thx
--
i.m.
The USA Patriot Act is the most unpatriotic act in American history. 12 101854
Ivan Marsh wrote: Anyone know how to test for the existance of a variable in javascript?
Check the 'typeof' operator:
<script type="text/javascript">
alert( typeof foo );
if(typeof foo == "undefined" ) {
// do stuff...
}
</script>
It's a good idea, when learning this property, to iterate over many
js/html types, in different user agents, to check the returned value.
You might be surprised sometimes (especially for "null" in js, and HTML
elements in Mozilla/IE).
HTH
Yep.
Ivan Marsh wrote: Anyone know how to test for the existance of a variable in javascript?
I'm looking for the equivalent of IsSet() from PHP. I'm having trouble finding it.
Not quite the same as isset in PHP but the JavaScript way is usually
if (typeof varname != 'undefined') {
// use varName
}
However that approach doesn't allow you to distinguish whether a
variable has not been declared or has been declared but not intialized,
that is if you declare
var varname;
then
typeof varname
is still 'undefined'. But that usually doesn't bother you as you only
want to check whether something useful is stored in the variable.
--
Martin Honnen http://JavaScript.FAQTs.com/
"Ivan Marsh" wrote on 11/11/2003: Hey Folks,
Anyone know how to test for the existance of a variable in
javascript? I'm looking for the equivalent of IsSet() from PHP. I'm having
trouble finding it.
Use this function:
function isSet( variable )
{
return( typeof( variable ) != 'undefined' );
}
It will work if a variable is defined, but not assigned to yet. For
example:
var a;
var b = 'used';
isSet( a ); // false
isSet( b ); // true
If you want to test for variables that have not been declared at all,
you have to test directly, or an error will occur. Continuing from
above:
if( typeof( c ) == 'undefined' )
{
// this will execute in this example
// c is not defined or has not been assigned to...
}
else
{
// c has been defined...
}
Mike
--
Michael Winter
M.Winter@[no-spam]blueyonder.co.u k (remove [no-spam] to reply)
> Anyone know how to test for the existance of a variable in javascript?
Runtime is not generally a good time to be checking that variables exist. It is
better to do it early with jslint. It produces a report that identifies
undeclared variables. It also reports declared but unused variables. http://www.crockford.com/javascript/lint.html
"Michael Winter" <M.Winter@[no-spam]blueyonder.co.u k> wrote in message
news:Vd******** **********@news-text.cableinet. net...
<snip> return( typeof( variable ) != 'undefined' );
<snip>
It is interesting that you have used parenthesise in the way you have in
the code above. They make typeof look like a function when it is an
operator that operates on an expression and return look like a function
call when it is a statement that may return an expression. That isn't
important for the execution of the code because JavaScript is very
tolerant of the presence (or absence) of white space, So:-
typeof(variable )
- is treated as if it was:-
typeof (variable)
- and - (variable) - is just a parenthesised expression. The parentheses
are serving no purpose so the effect is exactly the same as:-
typeof variable
While:-
return( ... );
- is treated as:-
return ( ... );
- and - ( ... ) - is another parenthesised expression, though in this
case parenthesising - typeof (variable ) != 'undefined' - would make it
clear that it is the result of evaluating the expression that is
returned and I would probably have done so myself (but I would have
placed a space before the "(").
No harmful consequences follow from the formulation of the original
code. Except possibly to blur the distinction between function calls and
the use of operators/statements, and maybe causing some confusion in the
minds of readers of the code.
Richard.
"Richard Cornford" wrote 11/11/2003: "Michael Winter" <M.Winter@[no-spam]blueyonder.co.u k> wrote in
message news:Vd******** **********@news-text.cableinet. net... <snip> return( typeof( variable ) != 'undefined' ); <snip>
It is interesting that you have used parenthesise in the way you
have in the code above. They make typeof look like a function when it is an operator that operates on an expression and return look like a
function call when it is a statement that may return an expression. That
isn't important for the execution of the code because JavaScript is very tolerant of the presence (or absence) of white space, So:-
typeof(variable )
- is treated as if it was:-
typeof (variable)
- and - (variable) - is just a parenthesised expression. The
parentheses are serving no purpose so the effect is exactly the same as:-
typeof variable
While:-
return( ... );
- is treated as:-
return ( ... );
- and - ( ... ) - is another parenthesised expression, though in
this case parenthesising - typeof (variable ) != 'undefined' - would make
it clear that it is the result of evaluating the expression that is returned and I would probably have done so myself (but I would have placed a space before the "(").
No harmful consequences follow from the formulation of the original code. Except possibly to blur the distinction between function calls
and the use of operators/statements, and maybe causing some confusion in
the minds of readers of the code.
I prefer to use parentheses wherever I can. I realise that typeof is
an operator, and is perfectly acceptable with, or without,
parentheses. I tend to surround all expressions and sub-expressions
with parentheses as I like not having to remember the operator
precedence table. I have enough to remember as it is, and not all
languages use the same precedence order. When I'm writing in C, C++
or Java, I even write return( true/false ), though I know it's not
necessary. It's part habit and part consistency.
Everyone has their own style, I suppose...
Mike
--
Michael Winter
M.Winter@[no-spam]blueyonder.co.u k (remove [no-spam] to reply)
On Tue, 11 Nov 2003 10:19:58 +0000, Douglas Crockford wrote: Anyone know how to test for the existance of a variable in javascript?
Runtime is not generally a good time to be checking that variables exist.
Yea, I know. What I was trying to do was get POST data easily into
JavaScript using PHP. Since the POST data isn't sent if the variable isn't
set I needed a way to check for unassigned variables. Instead I just
decided to add a default value if it's unassigned.
I originaly was doing:
print("<SCRIPT LANGUAGE='JavaS cript'>\n");
foreach ($_POST as $key_var => $value_var) {
print("var " . $key_var . " = '" . $value_var . "';\n");
}
print("</SCRIPT>\n");
Which worked fine for everything that's posted. But if you try to use a
variable that wasn't assigned from post data it would crash that
javascript you were referencing it from.
This is what I ended up with:
function JSPostVar($post var, $postvarval = "") {
print("<SCRIPT LANGUAGE='JavaS cript'>\n");
if (IsSet($_POST[$postvar])) {
print("var " . $postvar . " = '" . $_POST[$postvar] . "';\n");
}
else {
print("var " . $postvar . " = '" . $postvarval . "';\n");
}
print("</SCRIPT>\n");
}
Maybe not as pretty as it could be but it serves its purpose.
--
i.m.
The USA Patriot Act is the most unpatriotic act in American history.
"Michael Winter" <M.Winter@[no-spam]blueyonder.co.u k> wrote in message
news:D5******** ***********@new s-text.cableinet. net...
<snip> I prefer to use parentheses wherever I can.
I bet that you wouldn't claim that if you stopped and thought about it
;-) Given how liberally you could insert parentheses into JavaScript
source code, especially as you can re-parenthesis any existing
parenthesised expression so inserting them "wherever you can" would
become recursive, you would be unlikely to ever manage to complete the
code for your first function.
I realise that typeof is an operator, and is perfectly acceptable with, or without, parentheses. I tend to surround all expressions and sub-expressions with parentheses as I like not having to remember the operator precedence table. I have enough to remember as it is, and not all languages use the same precedence order. When I'm writing in C, C++ or Java, I even write return( true/false ), though I know it's not necessary. It's part habit and part consistency.
The parenthesising of (and within) expressions is not really the subject
of my quibble (and it is no more than that). I also do not bother to
memorise operator precedence in languages and instead use nested
parentheses to force (and express) my desired precedence (JavaScript's
automatic type conversion often makes that doubly desirable).
My comments were more aimed at the expression of the distinction between
a function call, in which the tradition is that the opening parenthesis
is not separated from the identifier or property accessor for the
function reference (even though it could be), and the nature of typeof
and void as operators and return as a statement. Which might be better
expressed by separating the expression from the operator/statement with
at least one space.
I mentioned it mostly because I often encounter people talking of "the
typeof function", "the void function" and (though very rarely) "the
return function". That is a misconception that could not easily arise
from reading the language documentation (or books on the subject) and I
suspect that it arises in the minds of authors new to JavaScript as a
result of seeing code that uses typeof (etc) in a function call-like
formulation.
Everyone has their own style, I suppose...
And so long as the resulting code executes nobody can stop you. But,
when posting in a group where some of the readers may reasonably be
expected to not be that experienced, would the cost of putting in the
odd extra space character to make code that represent function calls
distinct from code that is not a function call really be too much of an
inconvenience?
Richard.
"Richard Cornford" wrote on 11/11/2003: "Michael Winter" <M.Winter@[no-spam]blueyonder.co.u k> wrote in
message news:D5******** ***********@new s-text.cableinet. net... <snip>I prefer to use parentheses wherever I can. I bet that you wouldn't claim that if you stopped and thought about
it ;-) Given how liberally you could insert parentheses into
JavaScript source code, especially as you can re-parenthesis any existing parenthesised expression so inserting them "wherever you can" would become recursive, you would be unlikely to ever manage to complete
the code for your first function.
:p I realise that typeof is an operator, and is perfectly acceptable with, or without, parentheses. I tend to surround all expressions and sub-expressions with parentheses as I like not having to remember the operator precedence table. I have enough to remember as it is, and not all languages use the same precedence order. When I'm writing in C, C++ or Java, I even write return( true/false ), though I know it's not necessary. It's part habit and part consistency.
The parenthesising of (and within) expressions is not really the
subject of my quibble (and it is no more than that). I also do not bother
to memorise operator precedence in languages and instead use nested parentheses to force (and express) my desired precedence
(JavaScript's automatic type conversion often makes that doubly desirable).
My comments were more aimed at the expression of the distinction
between a function call, in which the tradition is that the opening
parenthesis is not separated from the identifier or property accessor for the function reference (even though it could be), and the nature of
typeof and void as operators and return as a statement. Which might be
better expressed by separating the expression from the operator/statement
with at least one space.
I mentioned it mostly because I often encounter people talking of
"the typeof function", "the void function" and (though very rarely) "the return function". That is a misconception that could not easily
arise from reading the language documentation (or books on the subject)
and I suspect that it arises in the minds of authors new to JavaScript as
a result of seeing code that uses typeof (etc) in a function call-like formulation.
Everyone has their own style, I suppose... And so long as the resulting code executes nobody can stop you. But, when posting in a group where some of the readers may reasonably be expected to not be that experienced, would the cost of putting in
the odd extra space character to make code that represent function calls distinct from code that is not a function call really be too much of
an inconvenience?
I see your point (I saw it the first time), and it's a good one. I'll
try to take it into consideration in future.
Mike
--
Michael Winter
M.Winter@[no-spam]blueyonder.co.u k (remove [no-spam] to reply) This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Marcus |
last post by:
I'm having a problem that is baffling me... say I set a session variable
as so:
$_SESSION = "default";
Now if I test the following two conditionals:
if($_SESSION == "default")
and
|
by: lamar_air |
last post by:
I need an if statement to test if a variable exists in a pyton script
eg. if var1 exists:
do this
else:
do this
|
by: wg |
last post by:
Hey,
Can someone show my how to change the code below to check to see if a
variable exists rather than if the variable contains an empty string.
if (document.form.regionselection.value == "") {
missinginfo += "\n - Region";
|
by: Lauchlan M |
last post by:
I'm retrieving url variable information uses the Request.QueryString object,
eg:
if (Request.QueryString.HasKeys())
key
{
lblMyResult.Text = Request.QueryString;
}
else
{
|
by: Shapper |
last post by:
Hello,
How to determine if a Session Variable exists?
In Page_Load I need to check is Session("MyVar") Exists.
If it doesn't exist then I created it and give it a value:
Session("myVar") = "Value"
Thanks,
Miguel
| |
by: Adam J Knight |
last post by:
Hi all,
I am trying to test to see if a Session variable exists.
This was my initial attempt, and doesn't work
int intInstructorID = (Session.ToString() == null ?
Convert.ToInt32(Request.QueryString):
Convert.ToInt32(Session));
|
by: nutso fasst |
last post by:
Hi. Any way to do this from asp page in IIS4? Application.Contents.Remove is
IIS 5+. Setting variable to empty string does not remove variable.
thx,
nf
|
by: Mike |
last post by:
Hello,
How do I check to see if a GET varaible exists?
This is giving me an error message.
if (isset !($_GET))
{die('You must Have a Key to get in');
}
Thanks
|
by: zensunni |
last post by:
In a perfect world, I wouldn't have to do this, but I'm at the mercy of event scripting for a program.
there's an event that runs every so often that triggers an subroutine. I'd like to declare a variable in that subroutine, but not have to worry about it when an event triggers it again. If I just go:
Public variable As String
.. it will...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it. ...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
| |
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in...
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...
| |