booleans
In this module we will study booleans.
File Location
You should be located in the following file:
javascript-library
└── 0-PreWork
└── 1-HTML-Basics
└── 2-CSS-Basics
└── 3-JavaScript-Basics
04-booleans.js <----You will be working in this file in this module.Description
Simply put, boolean values allow us to set a variable to a true or false value. Very often, in programming, you will need a data type that can only have one of two values, such as:
YES / NO
ON / OFF
TRUE / FALSEFor this, JavaScript has a Boolean data type. It can only take the values true or false.
Examples
Here's how we can declare a boolean variable in JavaScript. Here we both declare the variable and initialize it with a boolean value.
var isLoggedIn = true;
var isAuthenticated = true;
var hasLoggedInToday = false;
var hasToken = false;Comparison Operators
Booleans are often used to compare two values for equality, inequality, or difference:
Operator
Meaning
==
Equality
===
Strict Equality
!=
Inequality
!==
Strict Inequality
>
Greater than
>=
Greater than or equal
<
Less than
<=
Less than or equal
Printing Values
We can play with the boolean operators and print a few items out:
console.log(2 > 1); //true
console.log(3 < 2); //false
var test = 2 >= 3; //What will this print?
console.log(test);
console.log("Two is greater than one? " + (2 > 1));
console.log(3 >= 1);Other Operations
Some other operations to see when dealing with equality.
Here's an important rule about == versus ===.
== checks to see if the values are the same. Not the type. === checks to see if the values and the equality are the same.
Expression
Result
Reason
2 == "2";
True
This checks for equality, not type.
1 == "1";
True
This checks for equality, not type.
2 === "2";
False
Equality is the same, but type is different.
2 === 2;
True
Equality and type are the same.
"Password12!!" === "Password12!!"
True
Equality and type are the same.
More Practice
Think it through: What would be the value for the following three?
"Password12!" === "Password12!!"
1 !== 2 //=> true
10 !== 10 //=> falseLogical Operators
These are important and fairly easy to memorize. Essentially, && is the equivalent of and, || means or, and ! or bang means not.
We gave some hard thinking examples to get your brain working with it:
&& stands for AND Example: 4 > 0 && -2 < 0 || stands for OR Example: 4 > 0 || -2 > 0 ! stands for NOT Example: !(posNum < 0)
Here are a few more examples that you can print:
console.log("&& :", 2===2 && 1===1 ); //true because?
console.log("|| :", 2===2 || 2===1 ); //true because?
console.log("!=", 2 != 1) //true because?Common Job Interview Question
What is the difference between == & === in JavaScript?
Last updated