DEV Community

reyes2981
reyes2981

Posted on

what i learned last week: if/else statements

I'm happy to share that I've officially completed week one of General Assembly's Java Immersive program. We dove into the command line, HTML/CSS and JavaScript. I haven't written in about two months so lets get right to it! I'll be going over if/else statements to solidify my knowledge in JavaScript.

The if statement executes a statement if a specified condition is truthy. If the condition is falsy, another statement can be executed.

if () {}

Let's dive into the above piece of code. Within the parentheses you'll need to write a conditional expression.

if (condition) {
statement1
}

First, I've declared a variable and stored the number 400 inside of it. Next, I created an if statement and added a condition inside of the parentheses.

let x = 400
if (x > 50) {
console.log("I'm larger than the number 50!");
}

Within the curly brackets I've gone ahead and created a statement. In this case I've written code that will show in the console ONLY if the condition returns a truthy value.

Remember, a truthy value is a value that is considered true when encountered in a Boolean context. See below for the group of values that are considered falsy in JavaScript. Note, all values outside of the group below are considered truthy.

falsy

What do you think will be the output when I run the above block of code. To confirm let's head over to the browser console.

INPUT

let x = 400
if (x > 50) {
console.log("I'm larger than the number 50!");
}

OUTPUT
I'm larger than the number 50!

Since 400 is larger than 50 the statement is displayed in the console. What if I want to display a different output if the number is less than 50? How would I set that up? In this case we can add an else statement to the above code.

let x = 41
if (x > 50) {
console.log("I'm larger than the number 50!");
} else {
console.log("I'm smaller than the number 50!");
}

Output

I'm smaller than the number 50!

The reason why we get the above output is because when the first condition was executed it resolved as falsy.

Let's check out a real world example.

function startAdventure() {
let local = prompt('Captian Picard has a mission for you in the Delta Quadrant. Do you take along riker or data?')
if (local === "riker") {
riker();
} else if (local === "data") {
data();
}
}

Above I have a function that allows the client to navigate prompts depending on their response.

Top comments (0)