Science Knowings: JavaScript Course For Social Media

Working with Booleans

Boolean Surprise!

Previously, we explored the world of numbers. Now, get ready to dive into the fascinating realm of booleans, the guardians of truth and falsehood in JavaScript.

What are Booleans?

Booleans are data types that represent logical values—either true or false. They play a crucial role in making decisions and controlling program flow.

Boolean Values

Only two possible values: true or false. True represents a positive or affirmative condition, while false indicates a negative or non-existent one.

Boolean Operators

Operators like && (AND), || (OR), and ! (NOT) are used to combine and manipulate boolean values.

AND Operator (&&)

x && y

Returns true if both x and y are true. Otherwise, returns false.

OR Operator (||)

x || y

Returns true if either x or y is true. Returns false only if both are false.

NOT Operator (!) (Negation)

!x

Reverses the boolean value. If x is true, it returns false. If x is false, it returns true.

Equality Operators (==, ===)

x == y

Compares two values for equality. Returns true if they are equal in value.

x === y
is the strict equality operator, which also checks for data type equality.

Inequality Operators (!=, !==)

x != y

Compares two values for inequality. Returns true if they are not equal in value.

 x !== y
is the strict inequality operator, which also checks for data type inequality.

Short-circuit Evaluation

When using AND and OR operators, JavaScript evaluates operands from left to right. If the result is already determined, it stops evaluating further operands, making it more efficient.

Truthy and Falsy Values

In JavaScript, some values are considered truthy, while others are falsy. Truthy values evaluate to true in boolean contexts, while falsy values evaluate to false.

Truthy Values

  • Non-zero numbers
  • Non-empty strings
  • true
  • Any non-null object
  • [] (empty array)
  • {} (empty object)

Falsy Values

  • 0
  • Empty string ("")
  • false
  • null
  • undefined
  • NaN (Not a Number)

Converting Strings to Booleans

Boolean(string)

Converts a string to a boolean value. An empty string ("") evaluates to false, while any non-empty string evaluates to true.

Converting Numbers to Booleans

Boolean(number)

Converts a number to a boolean value. 0 evaluates to false, while any non-zero number evaluates to true.

Booleans and Arrays

Arrays are collections of items, including booleans. You can store and manipulate boolean values within arrays using the same principles as other data types.

Next: Arrays and Array Methods

In the next session, we'll dive into the world of arrays and their powerful methods. Follow us to unlock the secrets of efficient data handling and manipulation.