Logic is an essential part of computer programming which affords for decisions to be made by the computer based on data or input.
JavaScript uses Boolean logic, which, like the Boolean
type itself, is named after George Boole, an English mathemtician who invented boolean algebra, in which all values can be reduced to true
or false
. This type of logic is useful in computer science because it is based on a binary number system, in which each bit has a value of 0 or 1.
Booleans
A boolean
is a datatype that can be either true
or false
.
In JavaScript other values will evaluate to false
, such as 0
, ""
(empty string), NaN
, null
, and undefined
. Everything else defaults to true
, such as "Hello World"
, 1
, 99
, or -99
. Try evaluating some booleans in the console with this syntax:
Boolean(true);
Boolean(false);
Boolean("");
Boolean(null);
Boolean(0);
Boolean(4);
Logical operators
Using comparison operators, we can test the values of variables to detect if they are equivalent.
Let's declare some variables:
var x = 1;
var y = 0;
var z = "1";
var a = 5;
And test to see if their value is equivalent:
x == y;
x != y;
x == z;
We can evaluate numeric values:
x > y;
x < y;
x >= z;
x <= a;
We can also test if their type is equivalent:
x === z;
x !== z;
operator | condition |
---|---|
== | two values are the same |
!= | two values are not the same |
> | value 1 is greater than value 2 |
< | value 1 is less than value 2 |
>= | value 1 is greater than or equal to value 2 |
<= | value 1 is less than or equal to value 2 |
=== | two values are the same and same type |
!== | two values are not the same or not the same type |
We can compare strings as well as numbers.
var x = "hello";
var y = "world";
x == y;
x != y;
Conditionals
Using booleans, we can make decision in our program with conditional statements starting with the keyword if
:
var answer = "hello world";
if ("hello world" == answer) {
console.log("Correct!");
}
var response = 10;
if (response != answer) {
console.log("That's incorrect.");
}
We can evaluate statements using numbers and strings as well:
var x = 0;
var y = 1;
if (x == y) {
console.log("x is equal to y");
}
if (x < y) {
console.log("x is less than y");
}
var a = "hello";
var b = "world";
if (a.length = b.length) {
console.log("hello and world have the same number of characters");
}
if (a == b) {
console.log("hello and world are the same string");
}
else
We can use else
to tell our program what to do if the conditional is false:
if (a == b) {
console.log("hello and world are the same string");
} else {
console.log("hello and world are NOT the same string")
}
else if
else if
is to test further conditions that are not covered by a simple else
.
if (x == y) {
console.log("The values are equal.");
} else if (x < y) {
console.log(x + " is less than " + y);
} else {
console.log(x + " is greater than " + y);
}