Detecting existance of a variable

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

    #1

    Detecting existance of a variable

    How can I check whether or not a variable exists in a script? I'm
    thinking in terms of

    if (my variable exists) { myfunction(); }


    --
    --
    Fabian
    Visit my website often and for long periods!


  • Richard Cornford

    #2
    Re: Detecting existance of a variable

    "Fabian" <lajzar@hotmail .com> wrote in message
    news:bvpmgc$vhf 3q$1@ID-174912.news.uni-berlin.de...[color=blue]
    > How can I check whether or not a variable exists in a script? I'm
    > thinking in terms of
    >
    > if (my variable exists) { myfunction(); }[/color]

    if(typeof x != 'undefined'){
    ...
    }

    Is as near as you can get. But a variable that is declared but has not
    yet been assigned a value will also return 'undefined' from a typeof
    test. A declared variable could be said to "exist" but in reality this
    is probably suitable to your problem.

    Richard.


    Comment

    • KC Wong

      #3
      Re: Detecting existance of a variable

      > How can I check whether or not a variable exists in a script? I'm[color=blue]
      > thinking in terms of
      >
      > if (my variable exists) { myfunction(); }[/color]

      It's an ugly hack, but you can use a try...catch block to do it.

      try {
      var i = myVariable;
      // My variable is there...
      myFunction();
      } catch (exception) {
      // My variable is not there
      }


      HTH,

      KC


      Comment

      • Fabian

        #4
        Re: Detecting existance of a variable

        Richard Cornford hu kiteb:
        [color=blue]
        > "Fabian" <lajzar@hotmail .com> wrote in message
        > news:bvpmgc$vhf 3q$1@ID-174912.news.uni-berlin.de...[color=green]
        >> How can I check whether or not a variable exists in a script? I'm
        >> thinking in terms of
        >>
        >> if (my variable exists) { myfunction(); }[/color]
        >
        > if(typeof x != 'undefined'){
        > ...
        > }
        >
        > Is as near as you can get. But a variable that is declared but has not
        > yet been assigned a value will also return 'undefined' from a typeof
        > test. A declared variable could be said to "exist" but in reality this
        > is probably suitable to your problem.[/color]

        Thanks. That did the job. I have a javascript page separated into two
        files, a data file and a parser file. By checking for the existance of
        the variable, it can continue to handle the older version of the data
        file.


        --
        --
        Fabian
        Visit my website often and for long periods!


        Comment

        Working...