DEV Community

patricklcarrera
patricklcarrera

Posted on

If/else statements in JavaScript

if (condition) {
statement
}
else if (secondCondition) {
statement
}
else if (thirdCondition) {
statement
}
else
statement

This is a basic 'if else' statement that can be used in JavaScript. This logic could be applied to several code such as math problems, website responses, or just basic inputs of data!

e.g.

let hourOfDay = 18
if (hourOfDay > 0 && hourOfDay <=8)
console.log('I am sleeping right now')
else if (hourOfDay >= 9 && hourOfDay <=17)
console.log('I am in School!')
else if (hourOfDay >= 18 && hourOfDay <=24)
console.log('I am playing video games!')

So in this example, the if else statements are taking in the value of "hourOfDay" as a condition and executing the statements based on which of the statements it comes out as true. With practice and some muscle memory, you will be able to write your own conditions to your code!

Happy Coding.

Top comments (0)