Javascript Conditional Statements
Published on
Updated on
2 minute reading time
Javascript, like most other programming languages, include ways to run blocks of code when something meets a condition. Here, I will describe the most common ways to do so.
This post is part of my lecture series for Math I/O. There is no pre-reading for this lecture.
If Statement
To run a block of code when a condition is true, use an if statement.
if (condition) {
doSomething();
}
You can also run a block of code when a condition is false using the else statement.
if (condition) {
doSomething();
} else {
doSomethingElse();
}
Switch statement
If you want to check a variable for equality against multiple different cases, use a switch statement.
switch (variable) {
case condition1:
doSomething();
break;
case condition2:
doSomethingElse();
break;
default:
doSomethingCompletelyDifferent();
break;
}
The default statement runs when the variable doesn’t equal any of the cases.
While loop
To run a block of code over and over again until a condition is false, use a while loop.
while (condition) {
doSomething();
}
Don’t forget to include something in the loop that will eventually make the condition false, otherwise you run into an infinite loop. (Which is a loop that never stops repeating itself; most likely crashing your browser)
For loop
If you want to run something a certain amount of times, use a “for" loop. For loops can be broken down into three components: an initiating statement, a condition, and a statement that runs after every loop.
for (var i = 0; i < 5; i++) {
doSomething();
}
Here you have the initiating statement of var i = 0. From there you check, is i less than 5? Yes, so then we doSomething();. After we doSomething();, we add 1 to i. Now i equals 2. Is i still less than 5? Yes, so we doSomething();. Then we add 1 to i again. This loop will keep happening until i is not less than 5.
Conclusion
Having different control/conditional statements helps keep the state of any application you’re making. Did the user say not to notify them? Then don’t, otherwise (else) notify them. That’s all I have to say for this week. Hope this post helps you get a little more used to this big world called programming.
if (youLikeThisPost) {
console.log("Come back next week! :)");
} else {
console.log("Aww that's okay, you should give me another chance next week :)");
}
I recommend that you look at different perspectives of the same concepts. WebCheatSheet.com has a similar post to mine, check out what they had to say here.