1

I don't think my question duplicate with How do I return the response from an asynchronous call?

In orther language(C#) i see, a variable declare in a function or loop, When you out of function or loop they can't access variable has been declare in other function, but in javascript can.

 $(document).ready(function () {
        Text();
        Tex2();
    });
    function Text() {
        for (xxi = 0; xxi < 10; xxi++) {
            console.log(xxi);
            iix = 99;
        }
        console.log(xxi + iix);
        Tex2();
    }
    function Tex2() {
        console.log("What the hel:" + (xxi + iix));
    }

The result is:

enter image description here Is there anyone can explain detail for me? thanks.

Hong Van Vit
  • 2,884
  • 3
  • 18
  • 43
  • 3
    `iix = 99;` there's no declaration ... it's as if you had `window.iix = 99` ... and any reference to `iix` is like `window.iix` ... so, it works - to learn more, search for javascript scope chain - also, Tex2 is called once at the end of Tex1 and again in the document.ready – Jaromanda X Oct 14 '17 at 08:08
  • https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript/500459#500459 gives a good rundown of scoping in JavaScript. – DocMax Oct 14 '17 at 08:10
  • One thing that answer doesn't mention, @DocMax is why `iix` in this case is global – Jaromanda X Oct 14 '17 at 08:11
  • If you declare a variable without a keyword, it becomes a global variable. `a=1` is global but `var a = 1` or `let a = 1` are not. Though, javascript also uses scope chaining, but that's not the issue here. – Araymer Oct 14 '17 at 08:11
  • @Araymer - scope chaining is probably relevant to how `iix` and `xxi` are "visible" to Tex2 :p (I just realised BOTH iix and xxi are global :p) – Jaromanda X Oct 14 '17 at 08:12
  • @JaromandaX, Good point. I was hesitant to propose that this question was a duplicate of the other. Now I am very glad that I did not. – DocMax Oct 14 '17 at 08:13
  • Thanks, I has been tested, but out of lop no error. I has been test var xxi in for loop. Can you details for me? – Hong Van Vit Oct 14 '17 at 08:22
  • @HồngVănVít Check the changed answer with clearer snippets. – Amit Kumar Singh Oct 14 '17 at 08:46

4 Answers4

3

You are declaring them as global variables without using var keyword. Use the var keyword to scope them to their intended scope or use "use strict" on top of javascript file. You can also use let keyword to scope them to their very local scope.

  1. Variables declared not using var and let keywords have global scope.

  2. Variables declared using var keyword are treated by javascript as first statement inside their closed scope or function. So, it defines a variable globally, or locally to an entire function regardless of block scope.

  3. let keyword allows to declare variables limited in scope to the block, statement, or expression on which it is used.

I have created 3 snippets below. one with let keyword, one with var keyword, and one with use strict keyword over your code. Run to see changing behavior of same code piece.

SNIPPETS BELOW

let keyword snippet. Run to see that variable is not available outside block scope even.

//let keyword snippet. See variable is not available outside block scope even.

$(document).ready(function () {
        Text();
        Tex2();
    });
    function Text() {
        for (let xxi = 0; xxi < 10; xxi++) {
            console.log(xxi);
           let iix = 99;
        }
        var xyz; 
        try
        {
          xyz = xxi + iix;
        } 
        catch (e){
          xyz = e;
        }
        console.log(xyz);
        Tex2();
    }
    function Tex2() {
    var abc;
     try
     {
      abc = (xxi + iix);
     } 
     catch (e){
        abc = e;
      }
        console.log("What the hel:" + abc);
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
var keyword snippet. Run to see that variable is not available outside function scope.
//var keyword snippet. See variable is not available outside function scope.

$(document).ready(function () {
        Text();
        Tex2();
    });
    function Text() {
        for (var xxi = 0; xxi < 10; xxi++) {
            console.log(xxi);
           var iix = 99;
        }
        var xyz; 
        try
        {
          xyz = xxi + iix;
        } 
        catch (e){
          xyz = e;
        }
        console.log(xyz);
        Tex2();
    }
    function Tex2() {
    var abc;
     try
     {
      abc = (xxi + iix);
     } 
     catch (e){
        abc = e;
      }
        console.log("What the hel:" + abc);
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

use strict keyword snippet. Run to see that it will not run at all. This is your code with use strict.

//Your snippet with "use strict". Will not work at all.
"use strict"

$(document).ready(function () {
        Text();
        Tex2();
    });
    function Text() {
        for (xxi = 0; xxi < 10; xxi++) {
            console.log(xxi);
            iix = 99;
        }
        console.log(xxi + iix);
        Tex2();
    }
    function Tex2() {
        console.log("What the hel:" + (xxi + iix));
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
Amit Kumar Singh
  • 4,393
  • 2
  • 9
  • 22
1

You need to declare the variable, otherwise the scope will be the same as window.iix. The below snippet has the result you expect (an error).

I've changed the line for (xxi = 0; xxi < 10; xxi++) { to for (var xxi = 0; xxi < 10; xxi++) {

 $(document).ready(function () {
        Text();
        Tex2();
    });
    function Text() {
     
        for (var xxi = 0; xxi < 10; xxi++) {
            console.log(xxi);
            iix = 99;
        }
        console.log(xxi + iix);
        Tex2();
    }
    function Tex2() {
        console.log("What the hel:" + (xxi + iix));
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
Dale
  • 1,911
  • 11
  • 18
1

When you don't use var to declare a variable, it's understand as a global variable.
What happened in your code won't happen again if you use var or let every time you declare a variable.

Jar3d
  • 116
  • 6
  • Thanks, I has been test, but out of lop no error. I has been test var xxi in for loop. Can you detail detail ? – Hong Van Vit Oct 14 '17 at 08:20
  • Try refreshing your console or run your code on another window's console. Your two variables should be declared with var keyword. After that if you run it it will throw an exception – Jar3d Oct 14 '17 at 08:47
1

Any variable which is not declared inside a function, is treated as a window variable:

    for (xxi = 0; xxi < 10; xxi++) {
        console.log(xxi); // this variable
        iix = 99; // this variable
    }

If you had done this, javascript won't read the variable outside the scope:

    for (var xxi = 0; xxi < 10; xxi++) {
        console.log(xxi);
        var iix = 99;
    }

Explained (Let's understand using declarations instead of looking for errors):

    var xxi = "one"; //global variable
    var iix = "two"; //global variable
    globalVar = "three"; // window variable i.e. window.globalVar
    var getValues = function () {
         var xxi; //local variable for the scope 
         var iix; //local variable for the scope 
         for (xxi = 0; xxi < 10; xxi++) {
            console.log(xxi); // takes the local variable
            iix = 99; //local change of value
         }
         globalVar = 100; //change of value to window variable accessible inside
    };
    getValues();
    var seeValues = function () {
        console.log(xxi); //"one" //Displays the value of global because the local variable of getValues() is not accessible outside
        console.log(iix); //"two" //Same as above
        console.log(globalVar); //100 and not "three" //Displays the altered window variable
    };
    seeValues();

See this link for detailed information: http://www.dotnettricks.com/learn/javascript/understanding-local-and-global-variables-in-javascript and What's the difference between a global var and a window.variable in javascript?

Harman
  • 298
  • 1
  • 13