If statements in JavaScript

Introduction Link to heading

if statements in JavaScript allow you to execute a block of code only if a specific condition is met. They are a fundamental tool to control the flow of your code.

Validation for two possible conditions Link to heading

if (true) {
  console.log("Hello");
} else {
  console.log("I am false"); // If the condition is false, this is executed
}

Validation for two or more possible conditions Link to heading

const age = 18;

if (age === 18) {
  console.log("You can vote, it will be your first time voting");
} else if (age >= 18) {
  console.log("You can vote again"); // If the previous condition is false, this is executed
} else {
  console.log("You cannot vote yet");
}

Ternary operator: Link to heading

  • It is a shorthand way of writing a simple if statement.
  • The syntax is condition? value if true : value if false.

Example Link to heading

const number = 1;

const result = number === 1 ? "I am one" : "I am not one";

console.log(result); // Prints "I am one"

##If inline:

  • You can use an inline if to execute a single line of code if a condition is met.
  • The syntax is condition && code.

Example: Link to heading

const isAdult = age >= 18;

console.log("The user is an adult: " + isAdult); // Prints "The user is an adult: true"

Keep learning about if statements to write more complex and adaptable JavaScript code!

<< Objects in JavaScript Switch statements in JavaScript >>