My code works, but the if/else if statements I used feel clunky. This is a common feeling I have when I'm writing code.
To improve code readability and reduce the perceived complexity, you need to reduce nesting, remove conditional branches, simplify if-conditions and switch to a more descriptive style. The following 'techniques' help to simplify your code sample:
1. Exploit the nested loop structure: The first if
condition checking for line-breaks becomes true
whenever the inner loop terminates. Get rid of the condition and move the statement below the inner loop body:
var size = 8;
var result = '';
for (var i = 0; i < size; i++) {
for (var j = 0; j < size; j++) {
if ((j % 2 === 0 && i % 2 === 0) || (j % 2 === 1 && i % 2 === 1)) {
result += ' ';
} else if ((j % 2 === 0 && i % 2 === 1) || (j % 2 === 1 && i % 2 === 0)) {
result += '#';
}
}
result += '\n';
}
2. Remove the redundant else if
condition: The final else if
condition is redundant as it is always true
when the first if-condition is false
. Remove it:
var size = 8;
var result = '';
for (var i = 0; i < size; i++) {
for (var j = 0; j < size; j++) {
if ((j % 2 === 0 && i % 2 === 0) || (j % 2 === 1 && i % 2 === 1)) {
result += ' ';
} else {
result += '#';
}
}
result += '\n';
}
3. Simplify the if
condition: Your if
condition can be expressed in terms of both loop iterators and thereby simplified to (j + i) % 2 === 0
:
var size = 8;
var result = '';
for (var i = 0; i < size; i++) {
for (var j = 0; j < size; j++) {
if ((j + i) % 2 === 0) {
result += ' ';
} else {
result += '#';
}
}
result += '\n';
}
4. Invert the negative if
condition: You can get rid of the explicit comparison to zero by switching your if
and else
statements:
var size = 8;
var result = '';
for (var i = 0; i < size; i++) {
for (var j = 0; j < size; j++) {
if ((j + i) % 2) {
result += '#';
} else {
result += ' ';
}
}
result += '\n';
}
5. Use the conditional ternary operator for terse conditional assignments: You can replace the somewhat verbose if else
statements with a single conditional assignment using the conditional ternary operator:
var size = 8;
var result = "";
for (var i = 0; i < size; i++) {
for (var j = 0; j < size; j++) {
result += (j + i) % 2 ? '#' : ' ';
}
result += '\n';
}
6. Replace the declarative loop with a more descriptive approach: Exploit built-in methods and introduce new named identifiers for self-documenting code:
function createBoard(size, black = '#', white = ' ') {
let even = (white + black).repeat(size / 2) + (size % 2 ? white : '') + '\n';
let odd = (black + white).repeat(size / 2) + (size % 2 ? black : '') + '\n';
return (even + odd ).repeat(size / 2) + (size % 2 ? even : '');
}
console.log(createBoard(7));