Conditionals

In JavaScript, conditional statements allow you to execute specific blocks of code based on whether a condition is true or false.

The if Statement

if statements in JavaScript use parentheses () to enclose the condition and curly braces {} to define the block of code to execute.

if (height > 4) {
  console.log("You are tall enough!");
}

else if and else

You can chain multiple conditions together using else if, and provide a fallback block using else.

if (height > 6) {
  console.log("You are super tall!");
} else if (height > 4) {
  console.log("You are tall enough!");
} else {
  console.log("You are not tall enough!");
}

Common Comparison Operators

We’ll cover these in more depth soon, but here are the basic comparison operators used within conditional statements:

  • === : equal to
  • !== : not equal to
  • < : less than
  • > : greater than
  • <= : less than or equal to
  • >= : greater than or equal to

Practical Example

A common use case for conditionals is validating that data falls within acceptable bounds before processing it.

let messageLen = 10;
let maxMessageLen = 20;

console.log(
  "Trying to send a message of length:",
  messageLen,
  "and a max length of:",
  maxMessageLen
);

if (messageLen <= maxMessageLen) {
  console.log("Message sent");
} else {
  console.log("Message not sent");
}