The benefits of declaring variables at the top of the function body in JavaScript

后端 未结 4 846
被撕碎了的回忆
被撕碎了的回忆 2021-02-04 17:43

I am reading Douglas Crockford\'s book \"Javascript: The Good Parts\". He is talking about scope and saying that JS doesn\'t have block scope:

In many mod

4条回答
  •  春和景丽
    2021-02-04 18:40

    From my point of view, as javascript do not have block scope, declaring all variables on top of the function makes you spot easier variables you do not have to use as you can reuse an other.

    Example :

    function test(){
        var pages = [
            'www.stackoverflow.com',
            'www.google.com'
        ];
    
        var users = [
            'John',
            'Bob'
        ];
    
        for (var page = 0; page < pages.length; page++) {
            console.log(pages[page]);
        };
    
        for (var user = 0; user < users.length; user++) {
            console.log(users[user]);
        };
    }
    

    Can be changed to :

    function test(){
        var index, pages, users;
    
        pages = [
            'www.stackoverflow.com',
            'www.google.com'
        ];
    
        users = [
            'John',
            'Bob'
        ];
    
        for (index = 0; index < pages.length; index++) {
            console.log(pages[index]);
        };
    
        for (index = 0; index < users.length; index++) {
            console.log(users[index]);
        };
    }
    

    And save one variable space from the memory.

    In such a small function the main point may not be visible, but imagine a whole project with thousand lines of code. This may make your code run faster.

提交回复
热议问题