To learn JavaScript, we must learn the basics.
In this article, we’ll look at the most basic parts of the JavaScript language.
if Statements
If statements let us run code conditionally.
For example, we can write:
const answer = prompt("Where's the capital of Italy?");
if (answer === "Rome") {
alert("Correct!");
}
to add a prompt to take in an answer to the question.
Then we check for it in th if
statement. If answer
is 'Rome'
, then we show the 'Correct!'
alert.
An if
statement if followed by a boolean expression we’re checking for.
If the boolean expression returns true
, then we run the code between the curly brace.
We should always use ===
to check for value equality since it checks for the type and value.
Simple if
statements may be written without curtly brackets or the statement may be written all in one line.
But it’s more convenient to read to have the curly braces because it’s clearer.
Comparison Operators
The ===
operator is the comparison operator.
It’s the equality operator.
It’s used to compare 2 things to see if they’re equal.
We can use the equality operator to compare the return value of any 2 expressions.
For example, we can write:
if (totalCost === 81.50 + 100) {
or
if (fullName === firstName + " " + "wong") {
String comparisons are case-sensitive, so only if both cases are the same then the strings are considered the same.
If we want to check if 2 expressions aren’t the same, then we can use the !==
inequality comparison operator.
So if we have:
"Rose" !== "rose"
then that returns true
since they have letters with different cases.
JavaScript comes with more operators.
They include >
for the greater-than operator.
<
is the less-than operator.
>=
is the greater than or equal to operator.
<=
is the less than or equal to operator.
We can use them by writing:
if (2 > 0) {
if (0 < 2) {
if (2 >= 0) {
if (2 >= 1) {
if (0 <= 2) {
if (1 <= 2) {
if…else and else if Statements
If we have more than one case to check for then we can use the else
keyword to add more cases.
For example, we can write:
const answer = prompt("Where's the capital of Italy?");
if (answer === "Rome") {
alert("Correct!");
} else {
alert("Wrong!");
}
The else
keyword is before the block that’s run when answer
isn’t 'Rome'
.
If we have more cases, then we can add the else if
statement.
For example, we can write:
const answer = prompt("Where's the capital of Italy?");
if (answer === "Rome") {
alert("Correct!");
} else if (answer === "Vatican") {
alert("Close!");
} else {
alert("Wrong!");
}
We run something is answer
is 'Vatican'
.
If answer
isn’t 'Rome'
or 'Vatican'
, then we run the last block.
Conclusion
JavaScript has the if
and else
keywords to let us create statements that let us run code conditionally.