CodeHS Answers: Unit 4 : If Statements
4.1.5: Is There a Ball?
// Karel should put a ball on the first spot // if there isn't one already there and then move. function start() { if(noBallsPresent()){ putBall(); } move(); }
Which general if statement definition is written correctly?
B
What does an if/else statement look like in JavaScript?
D
Why do we use if statements in JavaScript?
To do something only if a condition is true
Why do we use if/else statements in JavaScript?
To either do something if a condition is true or do something else
4.3.1: Face the Right Direction
function start() { if(noBallsPresent()){ turnAround(); } else { turnRight(); } }
4.2.4: One Ball in Each Spot
function start(){ checkBall(); move(); checkBall(); move(); checkBall(); move(); checkBall(); } function checkBall(){ if(noBallsPresent()){ putBall(); } }
4.2.5: Right Side Up
function start(){ if (facingSouth()) { turnRight(); } if (facingWest()) { turnAround(); } }
4.3.2: Fetch Puzzle
function start(){ if(facingEast()){ move(); takeBall(); } if(ballsPresent()){ takeBall(); } if( facingWest()){ turnAround(); } }
4.1.3: If Statements
function start(){ move(); if(frontIsClear()){ move(); } } /* You can try commenting in this start function to see what happened before. If we try to move twice here, then karel will crash into a wall. function start(){ move(); move(); } */
4.2.3: If/Else Statements
function start(){ move(); if(frontIsClear()){ move(); }else{ turnLeft(); } }
4.1.4: Safe Take Ball
function start(){ safeTakeBall(); move(); safeTakeBall(); } function safeTakeBall(){ if(ballsPresent()){ takeBall(); } }