Testing to see if a variable exists...

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Ivan Marsh

    Testing to see if a variable exists...

    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.

  • Yann-Erwan Perio

    #2
    Re: Testing to see if a variable exists...

    Ivan Marsh wrote:
    [color=blue]
    > Anyone know how to test for the existance of a variable in javascript?[/color]

    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.

    Comment

    • Martin Honnen

      #3
      Re: Testing to see if a variable exists...



      Ivan Marsh wrote:[color=blue]
      > 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.[/color]

      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


      Comment

      • Michael Winter

        #4
        Re: Testing to see if a variable exists...

        "Ivan Marsh" wrote on 11/11/2003:
        [color=blue]
        > Hey Folks,
        >
        > Anyone know how to test for the existance of a variable in[/color]
        javascript?[color=blue]
        >
        > I'm looking for the equivalent of IsSet() from PHP. I'm having[/color]
        trouble[color=blue]
        > finding it.[/color]

        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)


        Comment

        • Douglas Crockford

          #5
          Re: Testing to see if a variable exists...

          > 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.



          Comment

          • Richard Cornford

            #6
            Re: Testing to see if a variable exists...

            "Michael Winter" <M.Winter@[no-spam]blueyonder.co.u k> wrote in message
            news:Vd9sb.677$ fp.3473544@news-text.cableinet. net...
            <snip>[color=blue]
            > return( typeof( variable ) != 'undefined' );[/color]
            <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.


            Comment

            • Michael Winter

              #7
              Re: Testing to see if a variable exists...

              "Richard Cornford" wrote 11/11/2003:
              [color=blue]
              > "Michael Winter" <M.Winter@[no-spam]blueyonder.co.u k> wrote in[/color]
              message[color=blue]
              > news:Vd9sb.677$ fp.3473544@news-text.cableinet. net...
              > <snip>[color=green]
              > > return( typeof( variable ) != 'undefined' );[/color]
              > <snip>
              >
              > It is interesting that you have used parenthesise in the way you[/color]
              have in[color=blue]
              > 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[/color]
              function[color=blue]
              > call when it is a statement that may return an expression. That[/color]
              isn't[color=blue]
              > 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[/color]
              parentheses[color=blue]
              > 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[/color]
              this[color=blue]
              > case parenthesising - typeof (variable ) != 'undefined' - would make[/color]
              it[color=blue]
              > 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[/color]
              and[color=blue]
              > the use of operators/statements, and maybe causing some confusion in[/color]
              the[color=blue]
              > minds of readers of the code.[/color]

              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)


              Comment

              • Ivan Marsh

                #8
                Re: Testing to see if a variable exists...

                On Tue, 11 Nov 2003 10:19:58 +0000, Douglas Crockford wrote:
                [color=blue][color=green]
                >> Anyone know how to test for the existance of a variable in javascript?[/color]
                >
                > Runtime is not generally a good time to be checking that variables
                > exist.[/color]

                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.

                Comment

                • Richard Cornford

                  #9
                  Re: Testing to see if a variable exists...

                  "Michael Winter" <M.Winter@[no-spam]blueyonder.co.u k> wrote in message
                  news:D5bsb.837$ %X1.5119124@new s-text.cableinet. net...
                  <snip>[color=blue]
                  >I prefer to use parentheses wherever I can.[/color]

                  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.
                  [color=blue]
                  >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.[/color]

                  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.
                  [color=blue]
                  >Everyone has their own style, I suppose...[/color]

                  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.


                  Comment

                  • Michael Winter

                    #10
                    Re: Testing to see if a variable exists...

                    "Richard Cornford" wrote on 11/11/2003:
                    [color=blue]
                    > "Michael Winter" <M.Winter@[no-spam]blueyonder.co.u k> wrote in[/color]
                    message[color=blue]
                    > news:D5bsb.837$ %X1.5119124@new s-text.cableinet. net...
                    > <snip>[color=green]
                    > >I prefer to use parentheses wherever I can.[/color]
                    >
                    > I bet that you wouldn't claim that if you stopped and thought about[/color]
                    it[color=blue]
                    > ;-) Given how liberally you could insert parentheses into[/color]
                    JavaScript[color=blue]
                    > 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[/color]
                    the[color=blue]
                    > code for your first function.[/color]

                    :p
                    [color=blue][color=green]
                    > >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.[/color]
                    >
                    > The parenthesising of (and within) expressions is not really the[/color]
                    subject[color=blue]
                    > of my quibble (and it is no more than that). I also do not bother[/color]
                    to[color=blue]
                    > memorise operator precedence in languages and instead use nested
                    > parentheses to force (and express) my desired precedence[/color]
                    (JavaScript's[color=blue]
                    > automatic type conversion often makes that doubly desirable).
                    >
                    > My comments were more aimed at the expression of the distinction[/color]
                    between[color=blue]
                    > a function call, in which the tradition is that the opening[/color]
                    parenthesis[color=blue]
                    > is not separated from the identifier or property accessor for the
                    > function reference (even though it could be), and the nature of[/color]
                    typeof[color=blue]
                    > and void as operators and return as a statement. Which might be[/color]
                    better[color=blue]
                    > expressed by separating the expression from the operator/statement[/color]
                    with[color=blue]
                    > at least one space.
                    >
                    > I mentioned it mostly because I often encounter people talking of[/color]
                    "the[color=blue]
                    > typeof function", "the void function" and (though very rarely) "the
                    > return function". That is a misconception that could not easily[/color]
                    arise[color=blue]
                    > from reading the language documentation (or books on the subject)[/color]
                    and I[color=blue]
                    > suspect that it arises in the minds of authors new to JavaScript as[/color]
                    a[color=blue]
                    > result of seeing code that uses typeof (etc) in a function call-like
                    > formulation.
                    >[color=green]
                    > >Everyone has their own style, I suppose...[/color]
                    >
                    > 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[/color]
                    the[color=blue]
                    > 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[/color]
                    an[color=blue]
                    > inconvenience?[/color]

                    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)


                    Comment

                    • Lasse Reichstein Nielsen

                      #11
                      Re: Testing to see if a variable exists...

                      "Ivan Marsh" <annoyed@you.no w> writes:
                      [color=blue]
                      > 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");[/color]

                      I recommend against adding variables dynamically, mostly because it
                      makes it harder to reason about the program.

                      If anything, I would make an object that is always created, and then
                      add the value as a property of that object. Javascript has methods for
                      checking whether a property is set, e.g.:
                      if ("propertyNa me" in objectRef) {...

                      /L
                      --
                      Lasse Reichstein Nielsen - lrn@hotpop.com
                      DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
                      'Faith without judgement merely degrades the spirit divine.'

                      Comment

                      • Jim Ley

                        #12
                        Re: Testing to see if a variable exists...

                        On Tue, 11 Nov 2003 10:19:58 -0800, "Douglas Crockford"
                        <nospam@laserli nk.net> wrote:
                        [color=blue][color=green]
                        >> Anyone know how to test for the existance of a variable in javascript?[/color]
                        >
                        >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.[/color]

                        Except of course that in an unknown execution environment where your
                        code can be modified before it's executed, runtime is the only time
                        you can ensure that it's been declared, any time earlier you're only
                        checking that the code you wrote - if it runs declares it, that's a
                        very different thing.

                        Jim.
                        --
                        comp.lang.javas cript FAQ - http://jibbering.com/faq/

                        Comment

                        • Thomas 'PointedEars' Lahn

                          #13
                          Re: Testing to see if a variable exists...

                          Yann-Erwan Perio wrote:
                          [color=blue]
                          > Ivan Marsh wrote:[color=green]
                          >> Anyone know how to test for the existance of a variable in javascript?[/color]
                          >
                          > Check the 'typeof' operator:
                          >
                          > <script type="text/javascript">
                          > alert( typeof foo );
                          > if(typeof foo == "undefined" ) {
                          > // do stuff...
                          > }[/color]

                          Although there may be rare occasions where the above is useful, it is
                          better to "do stuff" if `foo' is _not_ undefined (i.e. typeof foo !=
                          "undefined" ). The gauntlet usually *prevents* access to undefined
                          variables, objects and properties.


                          PointedEars

                          Comment

                          Working...