Back to Course

Introduction to JavaScript

0% Complete
0/0 Steps
  1. JavaScript: Basics
    9Topics
    |
    10 Quizzes
  2. JavaScript: Variables
    9Topics
    |
    10 Quizzes
  3. JavaScript: Conditional Statements
    10Topics
    |
    11 Quizzes
  4. JavaScript: Functions
    10Topics
    |
    11 Quizzes
  5. JavaScript: Scope
    6Topics
    |
    7 Quizzes
  6. JavaScript: Arrays
    11Topics
    |
    12 Quizzes
  7. JavaScript: Loops
    8Topics
    |
    9 Quizzes
  8. JavaScript: High Order Functions
    3Topics
    |
    4 Quizzes
  9. JavaScript: Iterators
    5Topics
    |
    5 Quizzes
Lesson 3, Topic 4
In Progress

JavaScript: Logical Operators

Yasin Cakal 31 Oct 2021
Lesson Progress
0% Complete

We’ll be using booleans, true or false values while working with conditionals. The logical operators are operators in JavaScript that work with boolean values. To make our conditionals more sophisticated, we can use logical operators. There are three different types of logical operators:

  1. The AND operator &&.
  2. The OR operator ||.
  3. The NOT operator ! , also known as the bang operator.

When we use the && operator, we ensure that two conditions are met:

if (haveCar=true && licsence = true) {
  console.log('You can drive!');
} else {
  console.log('Stop! You cannot drive');
}

Both conditions must evaluate to true for the complete condition to evaluate to true and execute when using the && operator. If either condition is false, the && condition evaluates to false, and the else block will execute.

We can use the || operator if we just worry about one of the conditions being true:

if (stopLight === 'red' || stopLight === 'yellow') {
  console.log('Stop and Wait!');
} else {
  console.log('Go!');
}

In || operator only one of the requirements must evaluate to true for the total statement to evaluate to true. If either stopLight === 'red' or stopLight=== 'yellow' evaluates to true in the code sample above, the if condition will evaluate to true, and the code block will execute. The second condition in a || statement will not be checked if the first condition evaluates to true. The code in the else expression will only run if both comparisons are false.

The ! NOT operator is used to reverse or negate the value of a boolean:

let hungry= true;
console.log(!hungry); // Prints false
 
let weekend= false;
console.log(!weekend); // Prints true

Essentially, the ! operator receives a true value and returns a false value, or it receives a false value and returns a true value.

In conditional statements, logical operators are frequently used to add another layer of logic to our code.

Responses

Leave a Reply

%d bloggers like this: