Learn Programming Fundamentals
1 Programming Fundamentals
2 Variables Data Types
4 Strings
5 Arrays
6 Objects
8 Functions
In the previous chapter, we learned about writing conditions using comparison operators. But what if we need to make decisions based on multiple conditions or values? That's where logical operators come in and play a crucial role.
Let's understand this through a simple flowchart example:
In the depicted flowchart:
It has two variables x=9
and y=20
.
Inside the diamond shape representing the decision-making
, it checks if vlaue of x
is same as y
and value of x
is also greater than 20
.
If both the condition are true, it prints the message "True" in the left green box.
If the conditions are false, it prints the message "False" in the right red box.
To implement multiple conditions like those depicted in the flowchart, we need to understand and use logical operators. Let's delve into them.
&&
)The AND operator (&&
) returns true only if both of its operands are true; otherwise, it returns false. Here's how it works:
true && true
evaluates to true
.true && false
evaluates to false
.In programming, assuming x
and y
are two integer variables, we can use the AND operator to check two conditions simultaneously:
if (x == y && x > 20) { console.log("True"); // Prints True }
||
)The OR operator (||
) returns true if at least one of its operands is true; otherwise, it returns false. Consider these examples:
true || true
evaluates to true
.true || false
evaluates to true
.false || false
evaluates to false
.In programming, assuming x
and y
are two integer variables, we can use the OR
operator to check two conditions simultaneously:
if (x == y || x > 20) { console.log("True"); // Prints True }
!
)The NOT operator (!
) negates the value of its operand. It converts true to false and false to true:
!true
evaluates to false
.!false
evaluates to true
.In programming, assuming x
and y
are two integer variables, we can use the NOT
operator to check two conditions simultaneously:
if (!(x == y)) { console.log("True"); // Prints True }
These logical operators are crucial for constructing conditional statements and performing comparisons in programming. They help developers build robust and efficient algorithms by allowing them to express complex conditions concisely and accurately.