Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Marissa Biesecker
4,030 PointsWhy is my code logging undefined at the end?
I was working on a JavaScript challenge - Chess Board- from Eloquent JavaScript (http://eloquentjavascript.net/02_program_structure.html) and came up with my own solution that works, but it logs undefined at the end. And I'd like to know- Why?
Here is a link to my codepen. It's not very pretty bc I take notes as I work through the code. https://codepen.io/maribies/pen/WZyqXE
Here is the code I wrote as well-
var size = 8;
var symbol = function(size*1/2) { var result = ""; for (var count = 0; count < size; count++) result += "# "; return result; } var space = function(size*1/2) { var result = ""; for (var count = 0; count < size; count++) result += " #"; return result; }
function chessBoard() { var result = ""; for (var count = 0; count < (size*1/2); count++) result += console.log( symbol(size)), console.log(space(size)); };
console.log(chessBoard());
I understand that it might not be the 'best' solution, but I do want to understand why it also returns undefined at the end.
Thanks.
(Also, if it's worth it, is there a was to refactor this code to condense the # of lines? Thanks!)
1 Answer
Steven Parker
243,318 PointsThat happens because of the way you call the function:
console.log(chessBoard());
The function "chessBoard" doesn't return anything, so "undefined" is logged. But all you need is to call the function by itself, since it handles logging the board symbols to the console internally:
chessBoard();
Marissa Biesecker
4,030 PointsMarissa Biesecker
4,030 Pointsthat makes sense! thanks!