Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda If-Else Statements | If-Else Statements
JavaScript Ninja

book
If-Else Statements

In this chapter, we will explore the concept of if-else statements in JavaScript. If-else statements allow us to make decisions in our code based on certain conditions. This is a fundamental concept in programming that enables us to control the flow of our programs.

Understanding If-else Statements

An if-else statement evaluates a condition and executes a block of code if the condition is true. If the condition is false, it can execute an alternative block of code. This is how we can make our programs respond differently to different situations.

Here's the basic structure of an if-else statement:

const condition = true
if (condition) {
console.log("Condition is true")
} else {
console.log("Condition is false")
}
123456
const condition = true if (condition) { console.log("Condition is true") } else { console.log("Condition is false") }
copy

The "!" Symbol

The "!" symbol is used to negate a boolean expression. If a condition is true, using "!" will make it false, and vice versa. This can be very useful when you want to execute code only when a condition is not met.

For example:

const condition = false
if (!condition) {
console.log("Condition is false")
}
1234
const condition = false if (!condition) { console.log("Condition is false") }
copy

Example

Let's look at an example that uses if-else statements to help our ninja collect all the sushi on the map. The ninja will move around the grid, picking up sushi while avoiding walls.

js

ninja.js

copy
function ninjaController(ninja) {
while (!(ninja.objectUp() === "wall" && ninja.objectRight() === "wall")) {
if (ninja.objectRight() === "wall") {
ninja.goUp();
ninja.pickSushi();
}
ninja.goRight();
ninja.pickSushi();
}
}

In this example, the ninja will continue to move and pick up sushi until it encounters walls both above and to the right. The if-else statement checks if there is a wall to the right. If there is, the ninja moves up and picks up sushi. Otherwise, it moves to the right and picks up sushi.

Tarefa

Swipe to start coding

Solução

function ninjaController(ninja) {
for (let i = 0; i < 8; i++) {
ninja.goRight();
if (ninja.objectRight() === "wall") {
if (ninja.objectDown() === "wall") {
ninja.goUp();
} else {
ninja.goDown();
}
}
}
ninja.pickSushi();
}
Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 5. Capítulo 1
js

ninja.js

function ninjaController(ninja) {
// Write your code below
}
toggle bottom row
We use cookies to make your experience better!
some-alt