The if Statement: Conditional Execution - Images: Japanese
Hey everyone!
Building on the comparison operators and boolean values we covered in the last article, let's now look at something called the if statement.
An if statement means "if this condition is true, do this."
Let's look at a basic example.
if(true){
console.log("Executed!");
}
That's an if statement.
You write if, followed by (), and then put the code you want to run inside {}.
If what's inside the () is true, the code inside {} runs. If it's false, it doesn't run.
In the example above, the condition is true, so console.log("Executed!"); gets executed.
You can also chain on an else statement right after. Like this:
if(false){
console.log("Executed!");
}
else{
console.log("Executed! (2)");
}
When the condition in the if is false, the code inside the else block runs unconditionally.
In the example above, the if condition is false, so console.log("Executed! (2)"); runs.
There's also an else if statement.
if(false){
console.log("Executed!");
}
else if(true){
console.log("Executed! (2)");
}
This lets you add another conditional branch after the initial if.
In the example above, the first if is false, so execution moves to the else if, which is true — so console.log("Executed! (2)"); runs. The difference from else is that else if lets you add yet another condition, rather than running unconditionally.
You can combine multiple else if statements and an else statement.
if(false){
console.log("Executed!");
}
else if(false){
console.log("Executed! (2)");
}
else{
console.log("Executed! (3)");
}
Here, the if is checked first, then the else if, and if both are false, the else block runs.
Note that the else statement must always come last.
if(false){ // This causes an error.
console.log("Executed!");
}
else{
console.log("Executed! (3)");
}
else if(false){
console.log("Executed! (2)");
}
The code above puts else if after else, which is an error. Also, you can't start with else if — the chain must always start with if. Keep both of these in mind.
Things are getting a bit more involved, so let's compare this with writing multiple separate if statements to make the difference clear.
if(true){
console.log("Executed!");
}
if(true){
console.log("Executed! (2)");
}
These are two completely independent if statements. Since both conditions are true, both console.log("Executed!"); and console.log("Executed! (2)"); run.
With else if, the next branch only gets evaluated if the first if is false — so the behavior is different from having two separate if statements. It's a bit tricky, but hopefully the basic idea is making sense.
Now let's put the comparison operators we learned earlier inside the () of an if statement.
if(1 < 2){
console.log("Executed!");
}
Look at what's inside the () — it says 1 < 2. That evaluates to true, so console.log("Executed!"); runs.
Now for a slightly more advanced angle.
In JavaScript, you can actually put values other than true and false inside the () of an if statement.
Take a look at this example.
if("hoge"){
console.log("Executed!");
}
Here, the string "hoge" is inside the (). Normally you'd expect a boolean there, so putting a string in might seem totally wrong.
But this actually gets treated as true, and the body of the if statement runs without any error. Interesting, right?
Now let's try an empty string.
if(""){
console.log("Executed!");
}
This gets treated as false, so the body doesn't run.
What's going on here?
The explanation is that in JavaScript, values are clearly divided into those treated as true and those treated as false.
Here's a reference table.
| A string (non-empty) | true |
| An empty string | false |
The number 0 |
false |
Any integer other than 0 |
true |
| null | false |
| undefined | false |
This isn't an exhaustive list, but those are the main cases. Other programming languages have a similar concept, but the specifics vary quite a bit — so treat this table as JavaScript-specific and memorize it as-is.
Pay particular attention to 0, 1, null, and undefined.
In programming, 0 and 1 are especially common values. Make sure you remember that 0 is treated as false.
Next, let's focus on null. It's treated as false.
Recall the document.getElementById() function. It searches by the id name you pass in, and if no matching element is found, it returns null.
Take a look at the following. It calls document.getElementById("hoge"), but there's no HTML element with the id hoge anywhere on the page.
<p>Run the alert!</p>
<script>
var elem = document.getElementById("hoge");
elem.addEventListener("click", function(){
alert('hoge1');
}, false);
</script>
Running this as-is assigns null to the variable elem, resulting in code like this:
null.addEventListener("click", function(){
alert('hoge1');
}, false);
That tries to attach an event listener to null, which is nonsensical and causes an error.
Let's combine this with an if statement to fix it.
<p>Run the alert!</p>
<script>
var elem = document.getElementById("hoge");
if(elem){
elem.addEventListener("click", function(){
alert('hoge1');
}, false);
}
</script>
Now the if statement checks whether elem is null before proceeding. Even if no element with the id hoge exists, there's no error.
This is why document.getElementById() is almost always paired with an if statement in practice.
Let's try one more example.
Think back to the code we wrote in this earlier article.
<p id="test">test</p>
<script>
function changeColor(id, font_color){
document.getElementById(id).style.color = font_color;
}
</script>
That's the function that changes text color. It doesn't use an if statement, which means if you pass in an id that doesn't exist in the HTML, it'll throw an error.
<p id="test">test</p>
<script>
function changeColor(id, font_color){
document.getElementById(id).style.color = font_color;
}
changeColor("hoge", "#0ff"); // Error — no element with id "hoge" found.
</script>
Adding an if statement lets us branch on "don't do anything" as a condition.
Let's add it in.
<p id="test">test</p>
<script>
function changeColor(id, font_color){
var elem = document.getElementById(id);
if(elem){
elem.style.color = font_color;
}
}
changeColor("hoge", "#0ff");
</script>
Much more robust now. A proper upgrade.
The example above stores the result in a variable first, but you can also write it directly inside the () like this:
<p id="test">test</p>
<script>
function changeColor(id, font_color){
if(document.getElementById(id)){
document.getElementById(id).style.color = font_color;
}
}
changeColor("hoge", "#0ff");
</script>
It's a bit of a tricky style, but it works. The author uses it when feeling lazy — though it's not a widely preferred pattern, so you may want to stick with the variable approach.
When an if, else if, or else block contains only a single statement, you can omit the curly braces {}.
if(true) console.log("hoge"); // This is valid too.
else if(false) console.log("hoge2");
else console.log("hoge3");
That said, many people find this harder to read, so it's generally not the recommended style.
For what it's worth, I personally don't find it hard to read at all and use it pretty freely — but that's just between us.
And that covers the if statement.
This article focused on the fundamentals. The if statement will keep coming up throughout the course, so you'll pick up new ways to use it as you go.
The next article covers logical operators — see you there!
This article was written by Sakurama.
Author's beloved small mammal |
桜舞 春人 Sakurama HarutoA Tokyo-based programmer who has been creating various content since the ISDN era, with a bit of concern about his hair. A true long sleeper who generally feels unwell without at least 10 hours of sleep. His dream is to live a life where he can sleep as much as he wants. Loves games, sports, and music. Please share some hair with him. |
If you find any errors or copyright issues, please contact us.