DEV Community

Cover image for Better Coding: JavaScript Conditionals
Alex Morton
Alex Morton

Posted on

Better Coding: JavaScript Conditionals

For my latest coding side project, Dice Game (adapted from my Jonas S. JS course on Udemy), one piece of the program's logic requires that rolling the die results in a variable holding a random number between 1 and 6. Depending on which number the variable logs, one of six images of the face of a die then shows up on the screen with a bit of nifty DOM manipulation.

When I was first writing out the code, my initial thought was to write out an if/else statement with all of the conditions of the random variable corresponding with each image of the face of the die, as follows:

let dice = Math.floor(Math.random() * 6) + 1;

let diceImage = document.querySelector('.dice');
diceImage.style.display = 'block';

if (dice === 1) {
  diceImage.src = 'dice-1.png';
} else if (dice === 2) {
  diceImage.src = 'dice-2.png';
} else if (dice === 3) {
  diceImage.src = 'dice-3.png';
} else if (dice === 4) {
  diceImage.src = 'dice-4.png';
} else if (dice === 5) {
  diceImage.src = 'dice-5.png';
} else if (dice === 6) {
  diceImage.src = 'dice-6.png';
}
Enter fullscreen mode Exit fullscreen mode

But then I learned that I could update the diceImage.src using type coercion by adding parts of the image name as a string with the corresponding image number sandwiched in between:

var diceImage = document.querySelector('.dice');
diceImage.style.display = 'block';
diceImage.src = 'dice-' + dice + '.png';
Enter fullscreen mode Exit fullscreen mode

Voilà! Three lines of code instead of sixteen!

It's things like this that make me really excited about JavaScript and its (and my!) capabilities. Not only are there a lot of cool programming concepts to keep learning, but there are also endless ways to make coding those programs more and more readable, clear, and effective.

This post was originally published on February 11, 2020 on my blog.

Top comments (0)