Javascript Cleaner Code Examples

Conditional assignment

If statement

// If 'truthy' is falsy, assign the value of 'falsy' to it
if (!truthy) {
    truthy = falsy;
}

Logical OR operator

truthy = truthy || falsy;

Ternary Examples

element ? (element.value = value) : console.error(`Element with ID "${id}" not found.`);

Instead of

if (element) {
    element.value = value;
} else {
    console.error(`Element with ID "${id}" not found.`);
}

Optional Chaining

ctx?.canvas?.width = config.width;

Combining Multiple Event Listeners for Optimisation

document.getElementById('clear-1')?.addEventListener('click', () => updateGameStats(1));
document.getElementById('clear-2')?.addEventListener('click', () => updateGameStats(2));
document.getElementById('clear-3')?.addEventListener('click', () => updateGameStats(3));
document.getElementById('clear-4')?.addEventListener('click', () => updateGameStats(4));

function updateGameStats(linesCleared: number) {
    // do stuff
}
const clearButtons = [1, 2, 3, 4];

clearButtons.forEach(linesCleared => {
    const button = document.getElementById(`clear-${linesCleared}`);
    if (button) button.addEventListener('click', () => updateGameStats(linesCleared));
});

the value, must be the same as the element id

const values = [1, 2, 3, 4];

values.forEach((linesCleared) => {
    const button = document.getElementById(`clear-${linesCleared}`);
    if (button) {
        button.addEventListener('click', () => incrementScore(linesCleared));
    }
});