var in JavaScript

  Peter        2012-05-26 12:35:36       3,633        0    

Geoff published an article sometime ago--"How one missing var ruined our launch". This article described one case where MelonCard uses Node.js as their backend system, suddenly there was a small registration peak period--50-100 people registered concurrently, then the entire website stopped responding and many other strange problems showed up. When they were investigating the source of the problem, they found one missing var in the following code.

app.all(‘/apps/:user_id/status’,
function(req, res, next) {
    // …
    initial = extractVariables(req.body);
});

Why does a missing var before initial cause this problem? If you don't have the var, the local variable now becomes a global variable. Much worse is that this variable is a function, so when many users are online concurrently, the variable which is not supposed to interfere with each other becomes a shared object. That means, user A's data may be overwritten by user B's data. The logic of the program is messed up.

On stackoverflow.com, there is one question "Difference between using var and not using var in JavaScript" discusses the difference between using var and not using var before variables.
// These are both globals
var foo = 1;
bar = 2;
 
function test()
{
    var foo = 1; // Local
    bar = 2;     // Global
 
    // Execute an anonymous function
    (function()
    {
        var wibble = 1; // Local
        foo = 2; // Inherits from scope above (creating a closure)
        moo = 3; // Global
    }())
}

The code snippet above says that if you don't use var, then the js engine will look up the scope chain until it finds the variable or hits the global scope( at which point it will create it). So if you want to declare a variable which is in current functional scope, you must use var.

Here is one tool JSLint( http://www.jslint.com/ ). It is a JS code quality analysis tool, if we copy the code snippet above into the tool, we will see the following report.

This report describes the variables in different functional scopes in the source code.

Original author :  Source : http://coolshell.cn/articles/7480.html#more-7480

JAVASCRIPT  VARIABLE  SCOPE 

       

  RELATED


  0 COMMENT


No comment for this article.



  RANDOM FUN

How normal people and developer look at coding