is the var keyword really necessary?

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

    #1

    is the var keyword really necessary?

    Hi,

    Is it recommended to use the var keyword when declaring a variable?

    IE lets me create a variable with var, then create the same one again
    with no problem.
    Also it lets me create a variable without the var keyword. As such the
    code below works fine:

    <html>
    <script>
    test = 1;
    var test2 = 2;
    var test = 3;
    var test2 = 4;
    alert(test);
    alert(test2);
    </script>
    </html>

    Also, is there a good reason not to do for statements like:

    for (li=0;li<10;li+ +){;}

    instead of:

    for (var li=0;li<10;li++ ){;}


    Cheers,
  • ZER0

    #2
    Re: is the var keyword really necessary?

    On 4 Oct 2004 07:39:22 -0700, Jack wrote:
    [color=blue]
    > Is it recommended to use the var keyword when declaring a variable?[/color]

    yes, 'cause you define the scope of your variables with var keyword.

    for example:

    var i=12; /* i is global */

    function foo(){
    var j=2; /* j is local */
    alert(i+j);
    }

    alert(i);
    foo();
    alert(j); /* error! j is local */

    try the same code without var keyword:

    i=12; /* i is global */

    function foo(){
    j=2; /* j is global as well */
    alert(i+j);
    }

    alert(i);
    foo();
    alert(j);

    As you see, without the var keyword all variables are global, and you could
    do overwrite some variable from function to another function.

    In addition, with "var" keyword you declare the variable, even if you don't
    assign it some value:

    var x;

    alert("x" in window); //true
    alert("y" in window); //false

    Hope it helps.

    P.S.
    Sorry for my english.

    --
    ZER0://coder.gfxer.web-designer/

    ~ "Massi' che e' uno standard, e' uno standard proprietario."
    (Gio')

    on air ~ "Motion City Soundtrack - My Favorite Accident"

    Comment

    • Christopher Benson-Manica

      #3
      Re: is the var keyword really necessary?

      Jack <jcwilliams@gma il.com> spoke thus:
      [color=blue]
      > Also, is there a good reason not to do for statements like:[/color]
      [color=blue]
      > for (li=0;li<10;li+ +){;}[/color]
      [color=blue]
      > instead of:[/color]
      [color=blue]
      > for (var li=0;li<10;li++ ){;}[/color]

      This second one is misleading, because li has function scope, not
      block scope (as the code seems to suggest). I personally choose
      neither, because as written they're hard to read.

      for( li=0; li < 10; li++ ) {;}

      Much easier IMHO.

      --
      Christopher Benson-Manica | I *should* know what I'm talking about - if I
      ataru(at)cybers pace.org | don't, I need to know. Flames welcome.

      Comment

      • Michael Winter

        #4
        Re: is the var keyword really necessary?

        On 4 Oct 2004 07:39:22 -0700, Jack <jcwilliams@gma il.com> wrote:
        [color=blue]
        > Is it recommended to use the var keyword when declaring a variable?[/color]

        For global variables, no, but it is considered good form. Starting with
        the var keyword makes it clear that the statement is a variable
        declaration (and possibly initialisation) .
        [color=blue]
        > IE lets me create a variable with var, then create the same one again
        > with no problem.[/color]

        I don't think it's a syntax error, but there isn't much point.
        [color=blue]
        > Also it lets me create a variable without the var keyword. As such the
        > code below works fine:
        >
        > <html>
        > <script>
        > test = 1;
        > var test2 = 2;
        > var test = 3;
        > var test2 = 4;
        > alert(test);
        > alert(test2);
        > </script>
        > </html>[/color]

        It is fine, because all of the variables are global.

        myVar = 1;

        and

        var myVar = 1;

        are identical at that scope level. The var keyword becomes very different
        within functions.
        [color=blue]
        > Also, is there a good reason not to do for statements like:
        >
        > for (li=0;li<10;li+ +){;}
        >
        > instead of:
        >
        > for (var li=0;li<10;li++ ){;}[/color]

        Again, in global scope, there isn't any problem. However, consider this[1]:

        function myFunction() {
        for(i = 0; i < 5; ++i) {
        // do something
        myFunction();
        }
        }

        When the function is called recursively, the variable, i, is reset to zero
        every time. When earlier invocations eventually regain control, i will
        always be five. That isn't likely to be the intended action.

        Getting into the habit of always using the var keyword is a good thing to
        do, in my opinion. It avoids problems that could arise if you forget to
        add it one time. Similarly, variables should *always* be limited in scope
        as much as possible. There are many ways to avoid placing globals
        everywhere, not limited to using objects and closures. Not only does it
        reduce the chances of errors, it also makes code more reusable by not
        polluting the global namespace.

        Mike


        [1] Ignore the infinite recursion for the moment. That isn't important for
        this example.

        --
        Michael Winter
        Replace ".invalid" with ".uk" to reply by e-mail.

        Comment

        • Michael Winter

          #5
          Re: is the var keyword really necessary?

          On Mon, 4 Oct 2004 14:54:18 +0000 (UTC), Christopher Benson-Manica
          <ataru@nospam.c yberspace.org> wrote:
          [color=blue]
          > Jack <jcwilliams@gma il.com> spoke thus:[/color]

          [snip]
          [color=blue][color=green]
          >> for (var li=0;li<10;li++ ){;}[/color]
          >
          > This second one is misleading, because li has function scope, not block
          > scope (as the code seems to suggest).[/color]

          That is true, if you're coming from a block scope background (I'm very
          much used to both), but most familiar with Javascript won't be confused by
          it. Moreover, if li is only used within the loop, there isn't much harm
          and I personally prefer it (though I'm used to function scope, I do prefer
          block scope).
          [color=blue]
          > I personally choose neither, because as written they're hard to read.
          >
          > for( li=0; li < 10; li++ ) {;}[/color]

          As in

          var li;

          for( li=0; li < 10; li++ ) {;}

          or do you use globals unless a situation demands otherwise?

          Mike

          --
          Michael Winter
          Replace ".invalid" with ".uk" to reply by e-mail.

          Comment

          • Michael Winter

            #6
            Re: is the var keyword really necessary?

            On Mon, 04 Oct 2004 14:58:51 GMT, Michael Winter
            <M.Winter@bluey onder.co.invali d> wrote:
            [color=blue]
            > On 4 Oct 2004 07:39:22 -0700, Jack <jcwilliams@gma il.com> wrote:
            >[color=green]
            >> Is it recommended to use the var keyword when declaring a variable?[/color]
            >
            > [...] no [...][/color]

            Oops. I was still considering the subject line which asked, "is the var
            keyword really necessary?"

            [snip]

            Mike

            --
            Michael Winter
            Replace ".invalid" with ".uk" to reply by e-mail.

            Comment

            • Christopher Benson-Manica

              #7
              Re: is the var keyword really necessary?

              Michael Winter <M.Winter@bluey onder.co.invali d> spoke thus:
              [color=blue]
              > That is true, if you're coming from a block scope background (I'm very
              > much used to both), but most familiar with Javascript won't be confused by
              > it. Moreover, if li is only used within the loop, there isn't much harm
              > and I personally prefer it (though I'm used to function scope, I do prefer
              > block scope).[/color]

              Well, if it's only used for the one loop, then it's fine. But in a
              complex script function with multiple loops, the C++ method would be

              for( int i=0; i < 10; i++ ) //
              ....
              for( int i=0; i < 10; i++ ) //

              Is redeclaring variables legal in JavaScript? jslint, in any case,
              does not allow it.
              [color=blue]
              > var li;
              > for( li=0; li < 10; li++ ) {;}[/color]

              I do that, on the assumption that redeclaration of variables is not
              technically legal; I may, of course, be mistaken (or misled by jslint,
              as the case may be).

              --
              Christopher Benson-Manica | I *should* know what I'm talking about - if I
              ataru(at)cybers pace.org | don't, I need to know. Flames welcome.

              Comment

              • Lee

                #8
                Re: is the var keyword really necessary?

                Jack said:[color=blue]
                >
                >Hi,
                >
                >Is it recommended to use the var keyword when declaring a variable?
                >
                >IE lets me create a variable with var, then create the same one again
                >with no problem.
                >Also it lets me create a variable without the var keyword. As such the
                >code below works fine:[/color]

                The var keyword doesn't do anything unless you are defining
                functions in your code, because without functions, all variables
                are global.

                When you start defining functions, you need to learn about scope
                rules and how the "var" keyword changes the scope of variables.

                Comment

                • Michael Winter

                  #9
                  Re: is the var keyword really necessary?

                  On Mon, 4 Oct 2004 15:17:59 +0000 (UTC), Christopher Benson-Manica
                  <ataru@nospam.c yberspace.org> wrote:

                  [snip]
                  [color=blue]
                  > Well, if it's only used for the one loop, then it's fine. But in a
                  > complex script function with multiple loops, the C++ method would be
                  >
                  > for( int i=0; i < 10; i++ ) //
                  > ...
                  > for( int i=0; i < 10; i++ ) //[/color]

                  In something like that, I'd probably move the declaration to the start of
                  the function. I'm used to doing that with MSVC++ which doesn't count the
                  variable declaration list of a for loop as a block (unless I'm getting
                  confused with another compiler...).
                  [color=blue]
                  > Is redeclaring variables legal in JavaScript? jslint, in any case,
                  > does not allow it.[/color]

                  I don't read anything in ECMA-262, and Mozilla (the most pedantic browser
                  I have) doesn't complain, so I'd say it's fine. Don't forget: JSLint
                  comments on style, as much as syntax, in order to prevent accidental
                  errors.

                  [snip]

                  Mike

                  --
                  Michael Winter
                  Replace ".invalid" with ".uk" to reply by e-mail.

                  Comment

                  • Richard Cornford

                    #10
                    Re: is the var keyword really necessary?

                    Michael Winter wrote:[color=blue]
                    > Christopher Benson-Manica wrote:[/color]
                    <snip>[color=blue][color=green]
                    >> Is redeclaring variables legal in JavaScript? jslint, in
                    >> any case, does not allow it.[/color]
                    >
                    > I don't read anything in ECMA-262, and Mozilla (the most
                    > pedantic browser I have) doesn't complain, so I'd say it's
                    > fine. Don't forget: JSLint comments on style, as much as
                    > syntax, in order to prevent accidental errors.[/color]

                    ECMA 262 does explicitly cover this in section 10.1.3 Variable
                    Instantiation:-

                    | Fore each VariableDeclara tion or VariableDeclara tionNoIn in
                    | the code, create a property of the variable object ...
                    | ... If there is already a property of the variable object
                    | with the name of a declared variable, the value of the
                    | property and its attributes are not changed. ...

                    And variable instantiation only happens once upon entering an execution
                    context. So you can declare the same variable as often as you like, only
                    one will ever exist as a result. Though it would be wasteful in time
                    take for variable instantiation and needlessly downloaded bytes to
                    re-declare variables (but not really the end of the world if it was only
                    re-declaring the same counter in two consecutive - for - loops).

                    Richard.


                    Comment

                    • Michael Winter

                      #11
                      Re: is the var keyword really necessary?

                      On Mon, 4 Oct 2004 17:39:28 +0100, Richard Cornford
                      <Richard@litote s.demon.co.uk> wrote:

                      [snip]
                      [color=blue]
                      > ECMA 262 does explicitly cover this [redeclaring variables] in section
                      > 10.1.3 Variable Instantiation:-[/color]

                      Ah. I didn't look in that section. I only checked 12.2 - Variable
                      statement, despite 10.1.3 being referenced twice.

                      [snip]

                      Thanks.

                      Mike

                      --
                      Michael Winter
                      Replace ".invalid" with ".uk" to reply by e-mail.

                      Comment

                      • Richard Cornford

                        #12
                        Re: is the var keyword really necessary?

                        Jack wrote:[color=blue]
                        > Is it recommended to use the var keyword when declaring
                        > a variable?[/color]

                        Yes.

                        Even when a global variable can be created (in effect) by nothing more
                        than assigning a value to an otherwise undeclared identifier, explicitly
                        declaring that identifier as a global variable in the global scope makes
                        it clear that the identifier is intended to be a global variable. That
                        clarity if for the benefit of humans reading the code; it prevents them
                        form wasting time trying to work out if the variable in question was
                        intended to be a global variable or whether they are looking at an
                        authoring mistake.

                        It is also the case that explicitly declared global variables are safer
                        to use because a read operation on an undeclared global variable that
                        takes the form of its (unqualified) identifier will throw a TypeError.
                        So code where one function attempts to create a global variable by
                        assigning to it, while another function reads from it, will error in the
                        second function if the first has not already been successfully executed.
                        If the same variable was explicitly declare the attempt to read its
                        value might return undefined but it would not error (the latter being
                        much easier to cope with).

                        Once you are writing functions - var - becomes essential because code
                        that attempts to use exclusively global variables soon ends up an
                        unmanageable spaghetti, where unplanned interactions in the global scope
                        produce intermittent errors that are difficult to identify and correct
                        (such code quickly exceeds the limited human ability to comprehend its
                        complexity). One programming principle, that certainly is applicable to
                        javascript, is: never give a variable more scope than it absolutely
                        needs. And using - var - to declare local variables in functions is the
                        mechanism for doing that.

                        Richard.


                        Comment

                        • bruce

                          #13
                          Re: is the var keyword really necessary?

                          jcwilliams@gmai l.com (Jack) wrote in message news:<dfb0b67a. 0410040639.6e4e 92f9@posting.go ogle.com>...[color=blue]
                          > Hi,
                          >
                          > Is it recommended to use the var keyword when declaring a variable?
                          >
                          > IE lets me create a variable with var, then create the same one again
                          > with no problem.
                          > Also it lets me create a variable without the var keyword. As such the
                          > code below works fine:
                          >
                          > <html>
                          > <script>
                          > test = 1;
                          > var test2 = 2;
                          > var test = 3;
                          > var test2 = 4;
                          > alert(test);
                          > alert(test2);
                          > </script>
                          > </html>
                          >
                          > Also, is there a good reason not to do for statements like:
                          >
                          > for (li=0;li<10;li+ +){;}
                          >
                          > instead of:
                          >
                          > for (var li=0;li<10;li++ ){;}
                          >
                          >
                          > Cheers,[/color]


                          If a system gets large enough, eventually you will use a field as
                          a local variable (without var), without realizing that it is a global
                          variable already. And finding the error isn't very easy.
                          For readability alone, it's advised to use var. It's also an act
                          of consideration for the next guy who comes along and has to read the
                          code.

                          Comment

                          Working...