local/global scope confusion

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

    local/global scope confusion

    Hi group,

    Consider this simple script (tested on FF3):

    <script type="text/javascript">
    test = 'outer';
    for (var i=0;i<2;i++){
    alert(test);
    var test = 'inner';
    alert (test);
    }
    alert (test);
    </script>


    I expected it would alert:
    (i==0): outer inner
    (i==1): ???? inner
    (after loop): outer

    I was just curious and wondered what the ???? would be.
    (It turns out that it is inner.)

    But what surprised me most was that the last alert, the one after the
    forloop, also gave me 'inner'.
    So it looks like declaring my local test variable affects the global
    test variable. I don't get that.

    Can anybody clarify to me why this happens?
    I must be missing something.

    TIA!

    Regards,
    Erwin Moller



    --
    "There are two ways of constructing a software design: One way is to
    make it so simple that there are obviously no deficiencies, and the
    other way is to make it so complicated that there are no obvious
    deficiencies. The first method is far more difficult."
    -- C.A.R. Hoare
  • Gregor Kofler

    #2
    Re: local/global scope confusion

    Erwin Moller meinte:
    Hi group,
    >
    Consider this simple script (tested on FF3):
    >
    <script type="text/javascript">
    test = 'outer';
    for (var i=0;i<2;i++){
    alert(test);
    var test = 'inner';
    alert (test);
    }
    alert (test);
    </script>
    >
    >
    I expected it would alert:
    (i==0): outer inner
    (i==1): ???? inner
    (after loop): outer
    >
    I was just curious and wondered what the ???? would be.
    (It turns out that it is inner.)
    JavaScript has function scope, not block scope. (Future versions of
    ECMAScript might allow block scoping, though.)
    But what surprised me most was that the last alert, the one after the
    forloop, also gave me 'inner'.
    So it looks like declaring my local test variable affects the global
    test variable. I don't get that.
    Since you are always in the same scope, you are always working with the
    same variable.
    Can anybody clarify to me why this happens?
    I must be missing something.
    Yes. There is no block scope in the current versions of JavaScript.

    Gregor

    Comment

    • Erwin Moller

      #3
      Re: local/global scope confusion

      Gregor Kofler schreef:
      Erwin Moller meinte:
      >Hi group,
      >>
      >Consider this simple script (tested on FF3):
      >>
      ><script type="text/javascript">
      >test = 'outer';
      >for (var i=0;i<2;i++){
      > alert(test);
      > var test = 'inner';
      > alert (test);
      >}
      >alert (test);
      ></script>
      >>
      >>
      >I expected it would alert:
      >(i==0): outer inner
      >(i==1): ???? inner
      >(after loop): outer
      >>
      >I was just curious and wondered what the ???? would be.
      >(It turns out that it is inner.)
      >
      JavaScript has function scope, not block scope. (Future versions of
      ECMAScript might allow block scoping, though.)
      >
      >But what surprised me most was that the last alert, the one after the
      >forloop, also gave me 'inner'.
      >So it looks like declaring my local test variable affects the global
      >test variable. I don't get that.
      >
      Since you are always in the same scope, you are always working with the
      same variable.
      >
      >Can anybody clarify to me why this happens?
      >I must be missing something.
      >
      Yes. There is no block scope in the current versions of JavaScript.
      >
      Gregor
      Thanks Gregor.

      I wonder why I never noticed in all the years I use JavaScript. ;-)
      /me goes shoot himself.

      The following script clearly shows what you said.

      <script type="text/javascript">
      var test = 'outer';
      function aFunc(){
      alert(test);
      for (var i=0;i<2;i++){
      var test = 'inner';
      alert (test);
      }
      }
      aFunc();
      alert (test);
      </script>

      gives: undefined, inner, inner, outer.
      As expected (once you know there is no block scope in current JavaScript).

      Thanks.

      Regards,
      Erwin Moller


      --
      "There are two ways of constructing a software design: One way is to
      make it so simple that there are obviously no deficiencies, and the
      other way is to make it so complicated that there are no obvious
      deficiencies. The first method is far more difficult."
      -- C.A.R. Hoare

      Comment

      • Martin Honnen

        #4
        Re: local/global scope confusion

        Gregor Kofler wrote:
        There is no block scope in the current versions of JavaScript.
        ECMAScript does not have it, but Mozilla's JavaScript has block scope
        since version 1.7 with let, see
        The MDN Web Docs site provides information about Open Web technologies including HTML, CSS, and APIs for both Web sites and progressive web apps.



        --

        Martin Honnen

        Comment

        • Conrad Lender

          #5
          Re: local/global scope confusion

          On 2008-11-12 11:12, Gregor Kofler wrote:
          JavaScript has function scope, not block scope.
          There is one minor exception to this rule (no pun inteded):

          var test = "outer";
          alert(test); // outer
          try {
          throw "inner";
          } catch (test) {
          alert(test); // inner
          }
          alert(test); // outer


          - Conrad

          Comment

          • Trevor Lawrence

            #6
            Re: local/global scope confusion

            "Erwin Moller"
            <Since_humans_r ead_this_I_am_s pammed_too_much @spamyourself.c omwrote in
            message news:491ab02b$0 $185$e4fe514c@n ews.xs4all.nl.. .
            >
            The following script clearly shows what you said.
            >
            <script type="text/javascript">
            var test = 'outer';
            function aFunc(){
            alert(test);
            for (var i=0;i<2;i++){
            var test = 'inner';
            alert (test);
            }
            }
            aFunc();
            alert (test);
            </script>
            >
            gives: undefined, inner, inner, outer.
            As expected (once you know there is no block scope in current JavaScript).
            >
            Thanks.
            >
            Regards,
            Erwin Moller
            I thought I understood the scoping of JavaScript, but now I don't

            So a variable declared and modified outside a function is not known inside
            the function ?
            But if a variable is declared and modified outside a function, it can be
            modified inside the function and its value is then known outside the
            function ??

            For example
            <script type="text/javascript">
            var test1 = 'outer1'; var test2 = 'outer2';
            alert('test1 ' + test1); alert('test2 ' + test2);

            function aFunc(){
            alert('test1 ' + test1); alert('test2 ' + test2);
            for (var i=0;i<2;i++){
            var test1 = 'inner1';
            test2 = 'inner2';
            alert('test1 ' + test1); alert('test2 ' + test2);
            }
            }
            aFunc();
            alert('test1 ' + test1);alert('t est2 ' + test2);
            </script>

            gives these alerts
            test1 outer1 ]
            test2 outer2 ] Outside function

            test1 undefined ]
            test2 outer2 ] Inside function - before loop

            test1 inner1 ]
            test2 inner2 ] Inside function - inside loop

            test1 inner1 ]
            test2 inner2 ] Inside function - inside loop

            test1 outer1 ]
            test2 inner2 ] Outside function

            Why is the variable test1 undefined at the start ?

            Is the function parsed before being executed so that JS knows that test1 is
            local, but is not actually defined until a line or so later?

            BTW,
            I may be that some explanations of the *meaning* of block scope and function
            scope could be useful here, and not just "JavaScript does not have block
            scope"
            --
            Trevor Lawrence
            Canberra
            Web Site http://trevorl.mvps.org


            Comment

            • Evertjan.

              #7
              Re: local/global scope confusion

              Trevor Lawrence wrote on 16 nov 2008 in comp.lang.javas cript:
              I thought I understood the scoping of JavaScript, but now I don't
              >
              So a variable declared and modified outside a function is not known
              inside the function ?
              No, and Yes:

              A variable declared outside a function is not known inside the function,
              only if a variable with the same name is declared inside that function.

              Javascript is not a linear parser, the parsing can be thougt of as a two
              phase process. In the first phase the names of variables and functions
              are defined with their scope, the second phase is the execution.

              [In fact the first phase probably also makes and optimizes an
              intermediate code.]

              The modification has nothing to do with is, but identifing these facts in
              your test.

              There are two different variables in the below code, both are named a.
              One has a global scope, the othe a scope local to f1().

              <script type="text/javascript">

              var a = 1;

              document.write( '<br>' + a); // 1 [global a]

              function f1(){
              document.write( '<br>' + a); // 1 [global a]
              };

              function f2(){
              document.write( '<br>' + a); // undefined [local scope a]
              var a = 2;
              document.write( '<br>' + a); // 2 [local scope a]
              };

              f1();
              f2();
              f1(); // 1 [global a]

              </script>



              --
              Evertjan.
              The Netherlands.
              (Please change the x'es to dots in my emailaddress)

              Comment

              • Jorge

                #8
                Re: local/global scope confusion

                On Nov 16, 7:34 am, "Trevor Lawrence" <Trevor L.@Canberrawrot e:
                >
                Is the function parsed before being executed so that JS knows that test1 is
                local, but is not actually defined until a line or so later?
                >
                Yes, that's it.

                --
                Jorge.

                Comment

                • Trevor Lawrence

                  #9
                  Re: local/global scope confusion

                  Thanks Evertjan and Jorge
                  Your answers gave precisely the info. I needed, even though my question may
                  have been a little unclear.

                  I have noticed that many other replies in this NG have not been as polite
                  and helpful

                  --
                  Trevor Lawrence
                  Canberra
                  Web Site http://trevorl.mvps.org

                  "Jorge" <jorge@jorgecha morro.comwrote in message
                  news:004e1857-6600-4806-8bb9-330b2ba2fefa@v3 9g2000pro.googl egroups.com...
                  On Nov 16, 7:34 am, "Trevor Lawrence" <Trevor L.@Canberrawrot e:
                  >
                  Is the function parsed before being executed so that JS knows that test1
                  is
                  local, but is not actually defined until a line or so later?
                  >
                  Yes, that's it.

                  --
                  Jorge.


                  Comment

                  • Evertjan.

                    #10
                    Re: local/global scope confusion

                    The Natural Philosopher wrote on 17 nov 2008 in comp.lang.javas cript:
                    The DOM is very weird.
                    The DOM is not part of Javascript.

                    Perhaps you mean the DOM-Javascript interface, but in IE that is the same
                    one as the DOM-VBS interface, so not Javascript specific.

                    <INPUT type FILEstuff is an abortion with respect to styling..
                    An abortion?
                    An abomination perhaps, but this does not touch Javascript at all.

                    Better switch to an HTML NG.

                    ;-)

                    --
                    Evertjan.
                    The Netherlands.
                    (Please change the x'es to dots in my emailaddress)

                    Comment

                    • The Natural Philosopher

                      #11
                      Re: local/global scope confusion

                      Evertjan. wrote:
                      The Natural Philosopher wrote on 17 nov 2008 in comp.lang.javas cript:
                      >The DOM is very weird.
                      >
                      The DOM is not part of Javascript.
                      >
                      Perhaps you mean the DOM-Javascript interface, but in IE that is the same
                      one as the DOM-VBS interface, so not Javascript specific.
                      >
                      Yup. See what I mean? where does the DOM stop and javashite begin?
                      >
                      ><INPUT type FILEstuff is an abortion with respect to styling..
                      >
                      An abortion?
                      An abomination perhaps, but this does not touch Javascript at all.
                      >
                      Better switch to an HTML NG.
                      >
                      see point above. Why doesn't javascript have PROPER access to these
                      elements?

                      ;-)
                      >
                      Indeed...

                      Comment

                      • Joost Diepenmaat

                        #12
                        Re: local/global scope confusion

                        The Natural Philosopher <a@b.cwrites:
                        Evertjan. wrote:
                        >The Natural Philosopher wrote on 17 nov 2008 in comp.lang.javas cript:
                        >><INPUT type FILEstuff is an abortion with respect to styling..
                        see point above. Why doesn't javascript have PROPER access to these
                        elements?
                        Because that would be incredibly stupid.

                        --
                        Joost Diepenmaat | blog: http://joost.zeekat.nl/ | work: http://zeekat.nl/

                        Comment

                        • Evertjan.

                          #13
                          Re: local/global scope confusion

                          The Natural Philosopher wrote on 17 nov 2008 in comp.lang.javas cript:
                          Evertjan. wrote:
                          >The Natural Philosopher wrote on 17 nov 2008 in comp.lang.javas cript:
                          >>The DOM is very weird.
                          >>
                          >The DOM is not part of Javascript.
                          >>
                          >Perhaps you mean the DOM-Javascript interface, but in IE that is the
                          >same one as the DOM-VBS interface, so not Javascript specific.
                          >>
                          >
                          Yup. See what I mean? where does the DOM stop and javashite begin?
                          Where does the land stop, and the sea begin?

                          Javascript is a far more general language than a clientside browser one.

                          Don't blame the German language for Hitler's behavour.
                          [Though I often would like to]

                          The DOM was not invented to accomodate Javascript.
                          >><INPUT type FILEstuff is an abortion with respect to styling..
                          >>
                          >An abortion?
                          >An abomination perhaps, but this does not touch Javascript at all.
                          >>
                          >Better switch to an HTML NG.
                          >>
                          >
                          see point above. Why doesn't javascript have PROPER access to these
                          elements?
                          Because the browser does not provide it, not a Javascript issue, but a
                          sensible one securitywize.


                          --
                          Evertjan.
                          The Netherlands.
                          (Please change the x'es to dots in my emailaddress)

                          Comment

                          • The Natural Philosopher

                            #14
                            Re: local/global scope confusion

                            Evertjan. wrote:
                            The Natural Philosopher wrote on 17 nov 2008 in comp.lang.javas cript:
                            >
                            >Evertjan. wrote:
                            >>The Natural Philosopher wrote on 17 nov 2008 in comp.lang.javas cript:
                            >>>The DOM is very weird.
                            >>The DOM is not part of Javascript.
                            >>>
                            >>Perhaps you mean the DOM-Javascript interface, but in IE that is the
                            >>same one as the DOM-VBS interface, so not Javascript specific.
                            >>>
                            >Yup. See what I mean? where does the DOM stop and javashite begin?
                            >
                            Where does the land stop, and the sea begin?
                            >
                            Javascript is a far more general language than a clientside browser one.
                            >
                            Don't blame the German language for Hitler's behavour.
                            [Though I often would like to]
                            >
                            The DOM was not invented to accomodate Javascript.
                            >
                            >>><INPUT type FILEstuff is an abortion with respect to styling..
                            >>An abortion?
                            >>An abomination perhaps, but this does not touch Javascript at all.
                            >>>
                            >>Better switch to an HTML NG.
                            >>>
                            >see point above. Why doesn't javascript have PROPER access to these
                            >elements?
                            >
                            Because the browser does not provide it, not a Javascript issue, but a
                            sensible one securitywize.
                            >
                            Theres a difference between being able to determine attributes of style,
                            and being able to rob the user of his files...

                            >

                            Comment

                            • Evertjan.

                              #15
                              Re: local/global scope confusion

                              The Natural Philosopher wrote on 17 nov 2008 in comp.lang.javas cript:
                              >>see point above. Why doesn't javascript have PROPER access to these
                              >>elements?
                              >>
                              >Because the browser does not provide it, not a Javascript issue, but a
                              >sensible one securitywize.
                              >>
                              >
                              Theres a difference between being able to determine attributes of style,
                              and being able to rob the user of his files...
                              >
                              Style is not Javascript, you could try CSS, but do reply in a PROPER NG.

                              --
                              Evertjan.
                              The Netherlands.
                              (Please change the x'es to dots in my emailaddress)

                              Comment

                              Working...