0

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).

4
  • 1
    var board; makes board initially undefined Commented Jan 10, 2017 at 23:30
  • When it goes through the for loops, doesn't it get populated? Commented Jan 10, 2017 at 23:32
  • 1
    Yes, but undefined + " " yields "undefined " Commented Jan 10, 2017 at 23:33
  • Ah, ok, I see, thank you! Commented Jan 11, 2017 at 1:40

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.