# Logical Operators

JavaScript Fundamentals: Logical Operators

### Can you name the logical operators in JavaScript?​

Interview Response: The logical operators in JavaScript are: AND (&&), OR (||), and NOT (!). They are used to perform logical operations on values or expressions.

### What makes the logical || (OR), && (AND), ! (NOT) operators unique?​

Interview Response: Logical operators in JavaScript work with any data type, not just Booleans. They assess operands based on truthiness and utilize short-circuiting for efficient, compact conditional expressions.

### If an operand is not a Boolean, what does the logical || OR do?​

Interview Response: If an operand is not a Boolean, the logical || OR operator will coerce the operands to Boolean values, then return the first truthy operand encountered or the last falsy one.

Code Example:

``/* Logical OR returns the first truthy value, *  or the last value if there are none */console.log('1' || '0'); // returns 1console.log(1 || 0); // returns 1console.log(0 || 0); // returns 0``

### How does logical OR “||” function?​

Interview Response: In JavaScript, the logical OR operator "||" returns the first truthy value it encounters when evaluating multiple operands, or the last operand if all are falsy. The OR || operator does the following:

1. Operands evaluate from left to right.
2. Converts each operand to a Boolean value, and if the result is true, the program terminates and returns the operand's original value.
3. Returns the final operand if all operands get evaluated (i.e., all were false).

Code Example:

``console.log(1 || 0); // 1 (1 is truthy)console.log(null || 1); // 1 (1 is the first truthy value)console.log(null || 0 || 1); // 1 (the first truthy value)console.log(undefined || null || 0); // 0 (all falsy, returns the last value)``

note

Logical OR “||” finds the first truthy value or the last value if there are none.

### What is the definition of a short-circuit evaluation in JavaScript?​

Interview Response: Short-circuit evaluation is a behavior of logical operators where subsequent operands are not evaluated if the previous operands are sufficient to determine the expression's value.

Code Example:

``true || console.log('not printed');false || console.log('printed');``

### What does the Logical && (AND) return?​

Interview Response: Logical && (AND) returns true if both operands are truthy and false otherwise.

Code Example:

``console.log(true && true); // trueconsole.log(false && true); // falseconsole.log(true && false); // falseconsole.log(false && false); // false``

### What type of conversion does the Logical && (AND) perform?​

Interview Response: The logical && (AND) performs a Boolean conversion. It evaluates two operands and returns true if both operands are true, and false otherwise.

Code Example:

``let x = 5;let y = 10;if (x > 0 && y < 20) {  console.log("Both conditions are true!");} else {  console.log("At least one condition is false.");}``

In this example, the logical AND operator (`&&`) is used to check if both `x` is greater than 0 and `y` is less than 20. If both conditions are true, it will print "Both conditions are true!" to the console. Otherwise, it will print "At least one condition is false."

### What steps does JavaScript perform when using the Logical && (AND) operator?​

Interview Response: Operands evaluate from left to right, then it converts each operand to a boolean value, and if the result is false, the program terminates and returns the operand's original value. It returns the final operand if all operands evaluate to true.

1. Operands evaluate from left to right.
2. Converts each operand to a Boolean value, and if the result is false, the program terminates and returns the operand's original value.
3. It returns the final operand if all operands get evaluated (i.e., all were true).

Code Example:

``// if the first operand is truthy,// AND returns the second operand:console.log(1 && 0); // 0console.log(1 && 5); // 5// if the first operand is falsie,// AND returns it. The second operand is ignoredconsole.log(null && 5); // nullconsole.log(0 && 'no matter what'); // 0``

### What are the differences between Logical || (OR) and Logical && (AND) operators?​

Interview Response: The logical || (OR) returns true if at least one operand is true. The logical && (AND) returns true only if both operands are true.

Code Example:

``let x = 5;let y = 10;// Logical OR (||) exampleif (x > 0 || y > 20) {  console.log("At least one condition is true!"); // Logs "At least one condition is true!"} else {  console.log("Both conditions are false.");}// Logical AND (&&) exampleif (x > 0 && y > 20) {  console.log("Both conditions are true!");} else {  console.log("At least one condition is false."); // "At least one condition is false."}``

### Between Logical || (OR) and && (AND) operators which has higher operator precedence?​

Interview Response: The '&&' (AND) operator has higher operator precedence than the '||' (OR) operator in most programming languages.

Technical Response: The precedence of the AND && operator is greater than that of the OR || operator. As a result, the code a && b || c && d is effectively the same as if the && expressions were enclosed in parentheses: (a && b) || (c && d).

Code Example:

``let a = true;let b = false;let c = true;// Due to precedence, '&&' operation will be performed before '||' operationlet result = a || b && c; console.log(result);  // Outputs: true``

In this case, the `b && c` operation happens first due to `&&` having higher precedence, returning `false`. Then, `a || false` is evaluated, which results in `true`.

### Can you replace conditional if with OR (||) or && (AND)?​

Interview Response: Technically, Yes, but it is not recommended because it reduces readability.

Technical Response: Technically, we can do it, which goes against recommendations. Although the variant with && appears shorter, an if statement is more prominent and tends to be more readable.

Code Example:

``let x = 1;x > 0 && console.log('Greater than zero!');// the if example is cleaner and obviouslet x = 1;if (x > 0) console.log('Greater than zero!');``

### What steps does JavaScript perform when implementing the Logical! (NOT) operator?​

Interview Response: The NOT operator accepts a single argument, converts it to a Boolean, and returns the inverse value.

Technical Response: The operator accepts a single argument and does the following:

1. Converts the operand to a Boolean type: true/false.
2. Returns the inverse value.

Code Example:

``console.log(!true); // falseconsole.log(!0); // true``

### What happens when we apply the !! (DOUBLE NOT) to a value?​

Interview Response: The value is inverted twice, returning it to its original Boolean value.

Technical Response: The first NOT changes the value to Boolean and returns the inverse, whereas the second NOT reverses the process. Finally, we have a simple Value-to-Boolean translation (Boolean conversion).

Code Example:

``console.log(!!'non-empty string'); // trueconsole.log(!!null); // false``

### Is there a built-in object that performs in the same fashion as the !! (DOUBLE NOT) operator?​

Interview Response: Yes, the built-in Boolean() function performs similarly to the double NOT (!!) operator, converting values to their respective Boolean representations.

Technical Response: The built-in Boolean object performs this in the same fashion as the !! (DOUBLE NOT) operator.

Code Example:

``console.log(!!'non-empty string'); // trueconsole.log(!!null); // false// Example of the Boolean methodconsole.log(Boolean('non-empty string')); // trueconsole.log(Boolean(null)); // false``

### What has the highest operator precedence over all the logical operators?​

Interview Response: The logical NOT (!) operator has the highest precedence among all logical operators in JavaScript. It always executes first.

Technical Response: The precedence of NOT ! is the highest of all logical operators, so it always executes first, before && (AND) or || (OR).

### What values are considered falsy in JavaScript?​

Interview Response: In JavaScript, the following values are considered falsy: false, null, undefined, 0, NaN, and "" (empty string).

Code Example:

``let falsyValues = [false, 0, "", null, undefined, NaN];falsyValues.forEach(value => {    if (value) {        console.log(`\${value} is truthy`);    } else {        console.log(`\${value} is falsy`);    }});``

This code will output that each value in the `falsyValues` array is falsy.

### What is operator precedence in JavaScript?​

Interview Response: Operator precedence determines the order in which operators are evaluated in expressions involving multiple operators. Operators with higher precedence are evaluated first.

### How can you use Logical Operators to simplify complex conditions?​

Interview Response: Logical operators (`&&`, `||`, `!`) can simplify complex conditions by chaining or negating boolean expressions, enhancing code readability and reducing redundancy in conditions.

Code Example:

Let's consider this JavaScript example where you need to check if a user is valid.

Without logical operators:

``let userName = "John";let userAge = 20;if (userName !== "") {    if (userAge >= 18) {        console.log("User is valid");    } else {        console.log("User is not valid");    }} else {    console.log("User is not valid");}``

Now, the same thing with logical operators:

``let userName = "John";let userAge = 20;if (userName !== "" && userAge >= 18) {    console.log("User is valid");} else {    console.log("User is not valid");}``

As you can see, the code is more simplified and readable when using logical operators.