Difference Between && and || Operators in javaScript
In JavaScript, logical operators && (AND) and || (OR) are used to perform the logical operations on values. These operators are commonly used in the control flow and decision-making within the programs. Understanding the differences between these operators is essential for writing efficient and accurate code.
These are the following topics that we are going to discuss:
Table of Content
What is &&?
The && operator also known as the logical AND operator evaluates expressions from the left to right and returns the first falsy value encountered. If all values are truthy it returns the last value.
- Returns true if both the operands are true.
- Stops evaluation as the soon as it finds a falsy value.
Syntax:
condition1 && condition2
Example: This example shows the use of && operator.
let a = true;
let b = false;
console.log(a && b);
let c = 5;
let d = 10;
console.log(c < d && d > 0);
Output
false true
What is ||?
The || operator also known as the logical OR operator evaluates expressions from the left to right and returns the first truthy value encountered. If all values are falsy it returns the last value.
- Returns true if at least one operand is true.
- Stops evaluation as the soon as it finds a truthy value.
Syntax:
condition1 || condition2
Example: This example shows the use of || operator.
let a = true;
let b = false;
console.log(a || b);
let c = 0;
let d = 10;
console.log(c || d);
Output
true 10
Difference Between && and || Operator
Characteristics | && operator | || operator |
---|---|---|
Evaluation | Stops at the first falsy value | Stops at the first truthy value |
Returns | First falsy value or last value if all are truthy | First truthy value or last value if all are falsy |
Use Case | Checking if all conditions are true | Checking if at least one condition is true |
Short-circuiting | Yes | Yes |
Truthy/Falsy Values | Returns the last truthy value if all are truthy | Returns the first truthy value |
Common Application | Conditional statements and function calls | Default values fallback mechanisms |
Conclusion
The && and || operators are powerful tools in JavaScript for controlling the flow of logic in the code. Understanding their differences and characteristics allows to use them effectively in the various programming scenarios. While && is useful for ensuring all conditions are met. || is ideal for the ensuring at least one condition is satisfied or providing the default values. Mastering these operators will enhance the ability to the write concise and efficient JavaScript code.