Question

15.

What are Logical Operators in JavaScript

Answer

In JavaScript, logical operators are used to perform logical operations on values, typically used in conditions that evaluate to either true or false (Boolean values). These operators can work with both Boolean values directly or with values of other types, in which case they are converted to Boolean implicitly (truthy or falsy values). Here are the main logical operators in JavaScript:

1. Logical AND (&&)

  • Returns true if both operands are true; otherwise, returns false.
  • If the first operand is falsy, it returns the first operand. If the first operand is truthy, it returns the second operand.
    console.log(true && true); // true
    console.log(true && false); // false
    console.log('Hello' && 123); // 123

2. Logical OR (||)

  • Returns true if at least one of the operands is true; otherwise, returns false.
  • If the first operand is truthy, it returns the first operand. If the first operand is falsy, it returns the second operand.
    console.log(false || true); // true
    console.log(false || false); // false
    console.log('' || 'fallback'); // 'fallback'

3. Logical NOT (!)

  • Returns false if its single operand can be converted to true; otherwise, returns true.
  • It effectively inverts the Boolean value of the operand.
    console.log(!true); // false
    console.log(!0); // true

Truthy and Falsy Values

In the context of logical operations, JavaScript values can be categorized as either "truthy" or "falsy". A falsy value is a value that translates to false when evaluated in a Boolean context. JavaScript defines the following falsy values:

  • false
  • 0 and -0
  • "" (empty string)
  • null
  • undefined
  • NaN

All other values are considered truthy, meaning they evaluate to true in Boolean contexts.

Short-Circuit Evaluation

Logical operators in JavaScript use "short-circuit" evaluation to decide the result as soon as possible.

  • For && (Logical AND): JavaScript evaluates the second operand only if the first operand is truthy.
  • For || (Logical OR): JavaScript evaluates the second operand only if the first operand is falsy.

This behavior is useful for writing more concise and efficient code, such as setting default values or conditional execution:

let a;
let b = null;
let c = "Hello";

let result = a || b || c; // "Hello"

In the example above, result is assigned the value "Hello" because it's the first truthy value from left to right.

Support us ❤️

Buy Us A Coffee