This is an if condition:
let grade = 5
if (grade >= 10) {
console.log("This is a passing grade")
}
- The if keyword allows us to run code conditionally based on a certain condition.
- The condition inside the if will either be true or false.
- When the condition inside the if results in true, the code between the curly braces will be executed.
- When the condition inside the if results in false, the code between the curly braces will be skipped.
function getVotingMessage(age) {
if (age >=18) {
return "You are allowed to vote"
}
}
//Sample usage
console.log(getVotingMessage(20))
Branching
Branching allows you to fork off your code into different pathing rather than just a top to bottom approach. This introduces an issue where some code might not run.
This tool helps visualize your code flow. https://bogdan-lyashenko.github.io/js-code-to-svg-flowchart/docs/live-editor/index.html
Chapter Recap
- The if keyword allows us to run code conditionally based on a certain condition.
- The condition inside the if will either be true or false.
- The code between the curly braces will be executed when the condition inside the if results in true.
- When the condition inside the if results in false, the code between the curly braces will be skipped.
- if conditions allow us to do branching in our code.
- The code inside the body of the if may or may not be executed depending on the condition of the if.