Conteúdo do curso
JavaScript Course for Beginners: Fundamentals and Practice
Sobre a Aula

The Use of Logical Operators

Congratulations on reaching the last lesson of the module! In this final stage, we will explore the power of logical operators in JavaScript, tools that allow you to combine different conditions and make more complex decisions in your scripts.

“AND” Operator (&&)

The “AND” operator is represented by “&&” and returns true only if all conditions are true.

It’s like deciding to wear a long-sleeved shirt “AND” a jacket only if it’s cold “AND” raining.

Syntax:

if (condition1 && condition2) {
  // code block to be executed if both conditions are true
}

“OR” Operator (||)

The “OR” operator is represented by “||” and returns true if at least one of the conditions is true.

It’s like deciding to wear a T-shirt “OR” a short-sleeved shirt if it’s hot “OR” sunny.

Syntax:

if (condition1 || condition2) {
  // code block to be executed if at least one of the conditions is true
}

“NOT” Operator (!)

The “NOT” operator is represented by “!” and inverts the value of a condition.

It’s like deciding not to use an umbrella “NOT” when it’s raining.

Syntax:

if (!condition) {
  // code block to be executed if the condition is false
}

Mastering logical operators with an example:

Logical operators allow you to combine two or more conditions into a single expression, enabling the creation of more sophisticated scenarios in your scripts.

Imagine a program that checks if a user is of legal age and has a valid driver’s license to rent a car.

Logical operators enable you to make this check efficiently.

Example:

// Check if the user is of legal age and has a driver's license
if (age >= 18 && hasDriverLicense) {
  console.log("You can rent the car.");
} else {
  console.log("You cannot rent the car.");
}

// Check if the user did not enter an empty value
if (!value.isEmpty()) {
  // Process the entered value
} else {
  // Display an error message
}

Challenge:

  1. Create a JavaScript script that prompts the user for three numbers.
  2. Use logical operators to check if the first number is greater than the second and if the second number is less than the third.
  3. Display a message on the screen indicating whether the numbers are in ascending order.

Congratulations on completing Module 1! You have acquired the basic knowledge of control structures in JavaScript.

Keep exploring, practicing, and learning to become a proficient JavaScript developer.

Entrar na conversa
Rolar para cima