HTML Dog
Skip to navigation

Conditional

Logic is used to make decisions in code; choosing to run one piece of code or another depending on the comparisons made. This requires use of something called a conditional. There are a few different conditionals that you might want to use, but we’ll just focus the one used most commonly: if.

If

It’s very simple: if some logic (the condition) is true, run a block of code. You can also supply more code to be run if the condition is not true, and supply additional conditions and blocks of code to optionally be run. These forms are called if-else, as you’ll see below.

The most simple if statement looks something like this:


if (10 > 5) {
    // Run the code in here
}

The code between the braces - “{” and “}” - is called a block, and this one is linked to the if statement. It’s only run if the conditional (between the parentheses) is true.

10 is indeed greater than 5, so the code in the block would run.

If-else

The if-else form of an if statement is used to run an alternative piece of code if the conditional is not true. The code in the if block below will be ignored, for example - only the code in the else block will be run.


if (43 < 2) {
    // Run the code in here
} else {
    // Run a different bit of code
}