usr8800
usr8800

Reputation: 1

“undefined” error when checking “undefined” in an if statement

i'm new to javascript and i'm developing tetris game. i have written some piece of code and reused some code from other sites. But one of the function is causing me some problems and i'm getting an error as "undefined is not an object evaluating board[y][x]". The piece of code is pasted below:

var COLS=10, ROWS=20;
var board = [];
function run() {
ctx.clearRect( 0, 0, canvas.width, canvas.height );

ctx.strokeStyle = 'black';
for ( var x = 0; x < COLS; ++x ) {
    for ( var y = 0; y < ROWS; ++y ) {
        if ( board[ y ][ x ] ) {
            ctx.fillStyle = colors[ board[ y ][ x ] - 1 ];
            drawBlock( x, y );
        }
    }
}
}

i'm not understanding as why am i getting the error. i have tried executing it in both safari and IE 11 but the result is the same. i even tried using the typeof keyword in the if statement but there's no change. Could anyone please help me to get rid of this error.

thanks

Upvotes: 0

Views: 56

Answers (1)

Igor Milla
Igor Milla

Reputation: 2786

You cannot do board[ y ][ x ] if you haven't initialised the board variable properly. You are trying to execute next line:

board [0][0]

and what javascript would do, is, first it will try to get board[0] which will be undefined, then it will try to do undefined[0], which will fire the error:

undefined is not an object

You should first put some data into your board array, before running that loop.

Upvotes: 1

Related Questions