[Solved] What’s way to define variable is better and why?


Javascript is functionally scoped, so in the first way, a is defined globally, while in the second, it’s defined in the scope of the function DoSomething. Also note that in the first method, you’re calling DoSomething incorrectly. Instead of calling it after the timeout, you’re calling it immediately, and passing it’s result (which is nothing in this example) as the function paramter input to setTimeout. As Hogan said in the comments, you’d want setTimeout(function () { DoSomething(a); }, 1000);

Generally, you should avoid defining variables at the global scope, and try to define them within a function. You can do this on document ready with jQuery:

$(function() {
    var a;
    var DoSomething = function() {
        a = $(window).width();
    }
    setTimeout(DoSomething, 1000);
};

solved What’s way to define variable is better and why?