简体   繁体   中英

Javascript - Undefined var showing up in console

Likely a simple question but I wasn't sure what to search for to find an answer.

In working my way through Eloquent Javascript, the following:

var size = 8;
var board;

for (var y = 0; y < size; y++) {
  for (var x = 0; x < size; x++) {
    if ((x + y) % 2 == 0)
      board += " ";
    else
      board += "X";
  }
  board += "\n";
}
console.log(board);

Produces

undefined x x x x
x x x x 
 x x x x
x x x x 
 x x x x
x x x x 
 x x x x
x x x x 

If I change the board variable to var board = ""; this doesn't happen.

I don't understand why, could someone enlighten me?

I'm running this in jfiddle.net with the https://getfirebug.com/firebug-lite-debug.js set up an external resource (to get the console).

Your adding string values to an undefined variable. It was only declared not initialized, so you must initialize the variable before using it by setting equal to "".

To add to this answer. Whenever a variable is declared but not initialized, it is by default set to undefined, which denotes it has not been initialized with any value. This is why when you first add the string to it, it is getting appended to the undefined value. Instead of this, if you initialize the variable with "", it is initialized as an empty string, and thereafter when you add the string values, it results in exactly what you were looking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM