Sobes.tech
Junior

What are the features of logical operators?

sobes.tech AI

Answer from AI

Logical operators in Node.js (||, &&, !) have features related to their behavior and return values:

  • || (OR): Returns the first "truthy" operand or the last operand if all are "falsy".
  • && (AND): Returns the first "falsy" operand or the last "truthy" operand if all are "truthy".
  • ! (NOT): Converts the operand to a boolean value and returns its inverse.

Features are related to "type coercion to boolean" (truthiness/falsiness):

  • "Falsy" values: false, 0, '' (empty string), null, undefined, NaN.
  • All other values are considered "truthy".

Operators || and && are "short-circuit" operators: they stop evaluation as soon as the result is known.

// Example of ||
const resultOr = 0 || 'hello' || true; // Returns 'hello'

// Example of &&
const resultAnd = 'hello' && 0 && true; // Returns 0

// Example of !
const resultNot = !'hello'; // Returns false
const resultNotNull = !null; // Returns true

Table of behavior for || and &&:

Expression Result Description
`a b`
`a b`
a && b a if a is falsy Returns a if a is falsy
a && b b if a is truthy Returns b if a is truthy
What are the features of logical operators? — Node.js - sobes.tech