Aim of this puzzle:
Use boolean control to determine the outcome of an SVG shape.
Walk through of the solution:
The boolean values of true
and false
can be used with if statements to control the flow of your code. If a condition is true
, then one block of code runs. If it’s false
, a different block of code runs instead.
In the code that you start off with, the sunOrMoon
function selects a time
from the times
array. If time
includes'pm'
, then it outputs a moon. If time
doesn’t include'pm'
, then it outputs a sun. As it is, the boolean control inside the if statement is incorrect - boolean values are not strings. As a result, the function always outputs a sun. In this puzzle, you’ll change the value from the string 'true'
to the boolean true
so the function runs properly.
To complete the puzzle, change'true'
to true
inside the if statement. Tap the play button inside Example Solution a few times to see the moon when a time
with 'pm'
gets picked.
Sample code solution:
(Tap below to reveal)
let times = ['7am', '9am', '5pm', '8pm'];
let circle = svg.append('circle').attr('r',50).attr('cx', 100).attr('cy', 50);
function sunOrMoon (times) {
let time = pickRandom(times);
if (time.includes('pm') === true){
circle.attr('fill', 'rgb(227,224,219)');
svg.append('circle').attr('r', 50).attr('cx', 130).attr('cy', 50).attr('fill', 'rgb(19,50,74)');
} else {
circle.attr('fill', 'rgb(252, 212, 64)');
}
console.log(time);
}
sunOrMoon(times);
JavaScript Concepts: Variable, If Statement, Boolean Control, String
D3 Concepts: Attribute, .append()