Condividi tramite


JavaScript scoping confuses other language developers.

 Developers who is writing in C#,C ++ and some other languages probably will 
face some bugs and uncommon behavior when will develop in JavaScript.

For me it was very confusing the scoping strategy in JavaScript so 
I have decided to drop some lines here.

First small sample about scoping in C#, this sample even will 
not compile since MyValue local variable declaration is not allowed 
when there is a global 

variable with the same name.

namespace ConsoleApplication3
{
    using System;

    class Program
    {
        static int MyValue = 10;
        
        static void Main(string[] args)
        {
            if (true)
            {
                int MyValue = 20;
            }

            Console.WriteLine("Final value: {0}", MyValue);
            Console.ReadKey();
        }
    }
}
 
But equivalent in JavaScript surprisingly will work and you 
can see that locally defined variable will have influence on global one, and
surprisingly (I think so) the output will be 20. 
 
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>Scope test</title>
</head>
<body>
<input type="button" onclick="TestScope()" value="Test" />
<script type="text/javascript">
var MyValue = 10;
function TestScope()
{
   if(true)
    {
       var MyValue = 20;
   }
   
    alert('Final value: ' + MyValue);
}
</script>
</body>
</html>
 
So scopes in JavaScript sometime can be more confusing if 
developer does not clearly understand the usage of var keyword.
I saw previously that developers just skip declaration of the variable 
and use it. Sure may be that worked but what is the price of omitting var?  
So variable which was used without var keyword will become global variable! 
Example will show that variable defined in Scope3 method will not 
affect global MyValue 
 <!DOCTYPE html>
<html>

<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>Scope test</title>
</head>
<body>
<script type="text/javascript">
function TestScope1()
{
   MyValue = 'Scope 1,';
}

function TestScope2()
{
    MyValue += 'Scope 2';
}

function TestScope3()
{
    var MyValue = 'Scope 3';
}
TestScope1();
TestScope2();
TestScope3();
alert(MyValue);
</script>
</body>
</html>