Using a local variable outside of its declaring scope; why does this work?

Dioxin

I got this game demo from a site, and noticed this piece of code:

if(nx == food.x && ny == food.y) {
    var tail = {x: nx, y: ny};
    score++;
    create_food();
} else {
    var tail = snake_array.pop(); 
    tail.x = nx; tail.y = ny;
}

snake_array.unshift(tail); //how is tail used here?

I didn't find any other declarations of a 'tail' variable, so how is this happening? I'm pretty new to this area of programming (web dev/scripting languages), so I'm not sure if this is allowed.

The full code:

$(document).ready(function(){
    var canvas = $("#canvas")[0];
    var ctx = canvas.getContext("2d");
    var w = $("#canvas").width();
    var h = $("#canvas").height();

    var cw = 10;
    var d;
    var food;
    var score;

    var snake_array; 

    function init() {
        d = "right"; 
        create_snake();
        create_food(); 
        score = 0;

        if(typeof game_loop != "undefined") clearInterval(game_loop);
        game_loop = setInterval(paint, 60);
    }
    init();

    function create_snake() {
        var length = 5; 
        snake_array = []; 
        for(var i = length-1; i>=0; i--) {
            snake_array.push({x: i, y:0});
        }
    }

    function create_food() {
        food = {
            x: Math.round(Math.random()*(w-cw)/cw), 
            y: Math.round(Math.random()*(h-cw)/cw), 
        };
    }                

    function paint() {
        ctx.fillStyle = "white";
        ctx.fillRect(0, 0, w, h);
        ctx.strokeStyle = "black";
        ctx.strokeRect(0, 0, w, h);

        var nx = snake_array[0].x;
        var ny = snake_array[0].y;

if(d == "right") nx++;
        else if(d == "left") nx--;
        else if(d == "up") ny--;
        else if(d == "down") ny++;

        if(nx == -1 || nx == w/cw || ny == -1 || ny == h/cw || check_collision(nx, ny, snake_array)) {
            init();
            return;
        }

        /* @@@@@@@@@ This is where it is happening @@@@@@@@@ */
        if(nx == food.x && ny == food.y) {
            var tail = {x: nx, y: ny};
            score++;
            create_food();
        } else {
            var tail = snake_array.pop(); 
            tail.x = nx; tail.y = ny;
        }

        snake_array.unshift(tail);

        for(var i = 0; i < snake_array.length; i++) {
            var c = snake_array[i];
            paint_cell(c.x, c.y);
        }

        paint_cell(food.x, food.y);
        var score_text = "Score: " + score;
        ctx.fillText(score_text, 5, h-5);
    }

    function paint_cell(x, y) {
        ctx.fillStyle = "blue";
        ctx.fillRect(x*cw, y*cw, cw, cw);
        ctx.strokeStyle = "white";
        ctx.strokeRect(x*cw, y*cw, cw, cw);
    }

    function check_collision(x, y, array) {
        for(var i = 0; i < array.length; i++) {
            if(array[i].x == x && array[i].y == y)
             return true;
        }
        return false;
    }

    $(document).keydown(function(e) {
        var key = e.which;
        if(key == "37" && d != "right") d = "left";
        else if(key == "38" && d != "down") d = "up";
        else if(key == "39" && d != "left") d = "right";
        else if(key == "40" && d != "up") d = "down";
    })
})

Source of code: http://thecodeplayer.com/walkthrough/html5-game-tutorial-make-a-snake-game-using-html5-canvas-jquery

Any help would be appreciated :)

Sterling Archer

tail was declared in an if statement, so it is not scope-limited to said statement. If it was in a function, you'd lose the scope.

As said in the comments, JavaScript only has function-level scoping.

Here's a simple example you can run in your console:

if (1>0) {
    var derp = "herp";
}
console.log(derp);
//outputs "herp"

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Java

Can a local variable's memory be accessed outside its scope?

From Dev

why is declaring inside for loop works but declaring outside for loop as global variable won't work

From Dev

Why declaring a controller as variable within itself or using $scope

From Dev

Can I use values of array declared as local variable outside of its scope?

From Dev

Prolog: how does variable instantiating work, what is the scope of local variables

From Dev

Prolog: how does variable instantiating work, what is the scope of local variables

From Dev

Why does printing a variable in global scope work, but modifying it does not?

From Dev

Why does printing a variable in global scope work, but modifying it does not?

From Dev

Why does it work with $scope but not with `this`?

From Dev

CppUnit: Why does a static local variable keep its value?

From Dev

Why can't I access local class outside declaring method?

From Dev

Why parseInt on a variable using expression does not display $scope variable?

From Dev

Why does this syntax not work for declaring associative array

From Dev

why does the order of variable declaring matter?

From Dev

why does the order of variable declaring matter?

From Dev

how does $scope in controllers work and different ways of declaring controllers?

From Dev

Why does the scope work like this?

From Dev

Why does setting a variable (outside of the object scope) equal to an object method return an undefined result?

From Dev

Why does setting a variable (outside of the object scope) equal to an object method return an undefined result?

From Dev

AngularJS: variable in ng-repeat without $scope is in its local scope?

From Dev

Why pi() function does not work in Oracle using its JDBC driver?

From Dev

Why does a variable of a function declared outside its function definition doesn't throw an error?

From Dev

Using local variable inside dynamic SQL does not work

From Dev

Pointer can point local variable's memory outside it's scope?

From Dev

List appears as null if used outside the local variable scope in Java

From Dev

Pointer can point local variable's memory outside it's scope?

From Dev

Why does javascript persist local variable reassignments that occur in outside functions without having to capture the return values?

From Dev

Why does javascript persist local variable reassignments that occur in outside functions without having to capture the return values?

From Dev

Why does global variable stay undefined even after assigning value to it in a local scope in javascript

Related Related

  1. 1

    Can a local variable's memory be accessed outside its scope?

  2. 2

    why is declaring inside for loop works but declaring outside for loop as global variable won't work

  3. 3

    Why declaring a controller as variable within itself or using $scope

  4. 4

    Can I use values of array declared as local variable outside of its scope?

  5. 5

    Prolog: how does variable instantiating work, what is the scope of local variables

  6. 6

    Prolog: how does variable instantiating work, what is the scope of local variables

  7. 7

    Why does printing a variable in global scope work, but modifying it does not?

  8. 8

    Why does printing a variable in global scope work, but modifying it does not?

  9. 9

    Why does it work with $scope but not with `this`?

  10. 10

    CppUnit: Why does a static local variable keep its value?

  11. 11

    Why can't I access local class outside declaring method?

  12. 12

    Why parseInt on a variable using expression does not display $scope variable?

  13. 13

    Why does this syntax not work for declaring associative array

  14. 14

    why does the order of variable declaring matter?

  15. 15

    why does the order of variable declaring matter?

  16. 16

    how does $scope in controllers work and different ways of declaring controllers?

  17. 17

    Why does the scope work like this?

  18. 18

    Why does setting a variable (outside of the object scope) equal to an object method return an undefined result?

  19. 19

    Why does setting a variable (outside of the object scope) equal to an object method return an undefined result?

  20. 20

    AngularJS: variable in ng-repeat without $scope is in its local scope?

  21. 21

    Why pi() function does not work in Oracle using its JDBC driver?

  22. 22

    Why does a variable of a function declared outside its function definition doesn't throw an error?

  23. 23

    Using local variable inside dynamic SQL does not work

  24. 24

    Pointer can point local variable's memory outside it's scope?

  25. 25

    List appears as null if used outside the local variable scope in Java

  26. 26

    Pointer can point local variable's memory outside it's scope?

  27. 27

    Why does javascript persist local variable reassignments that occur in outside functions without having to capture the return values?

  28. 28

    Why does javascript persist local variable reassignments that occur in outside functions without having to capture the return values?

  29. 29

    Why does global variable stay undefined even after assigning value to it in a local scope in javascript

HotTag

Archive