Introduction to Booleans
In JavaScript, booleans are a data type that can only have two values: true
or false
. They are typically used to represent the truth value of an expression or condition in a program. For example, you might use a boolean to represent whether a user is logged in to your website or not.
let loggedIn = true;
In the above example, loggedIn
is a boolean variable that is set to true
.
Comparison Operators and Booleans
Booleans are often used in conjunction with comparison operators to evaluate expressions. Comparison operators are used to compare two values and return a boolean value. Here are some of the comparison operators in JavaScript:
==
equal to!=
not equal to>
greater than<
less than>=
greater than or equal to<=
less than or equal to
let x = 5;
let y = 10;
console.log(x < y); // outputs true
console.log(x == y); // outputs false
In the above example, x
is less than y
, so console.log(x < y)
returns true
. x
is not equal to y
, so console.log(x == y)
returns false
.
Logical Operators and Booleans
Logical operators are used to combine or invert boolean expressions. There are three logical operators in JavaScript:
&&
logical and||
logical or!
logical not
let a = true;
let b = false;
console.log(a && b); // outputs false
console.log(a || b); // outputs true
console.log(!a); // outputs false
In the above example, console.log(a && b)
returns false
because a
is true and b
is false. console.log(a || b)
returns true
because at least one of a
or b
is true. console.log(!a)
returns false
because the logical not operator inverts the value of a
.