If Statement
Part of the Fundamentals section of Coddy's JavaScript journey — lesson 23 of 77.
If statements allow us to execute code with conditions.
For example, let's look at the following code:
let age = 20;
let status = "Child";
if (age > 18) {
status = "Adult";
}
age += 1;The above code checks whether the age variable is bigger than 18. If it is, it will set status to hold "Adult" string.
In the end, the code will increment age by 1 whether the age is bigger than 18 or not.
To use an if statement we need to add parenthesis () that will determine the condition, and everything that is inside the if is in curly braces {}:
if (condition) {
code;
code;
code;
}If the condition is true, we will enter the code block inside the if (the code inside the curly braces)
Challenge
BeginnerYou are given a code.
The variables a and b have missing values, fill them so that the code inside the if statement will be executed!
Bonus: try to find more than one solution!
Cheat sheet
If statements execute code when a condition is true:
if (condition) {
// code to execute
}Example:
let age = 20;
let status = "Child";
if (age > 18) {
status = "Adult";
}The condition goes inside parentheses () and the code to execute goes inside curly braces {}.
Try it yourself
let a = ?
let b = ?
// Don't change below this line
let c = 0;
if (a >= b && !(b < 10)) {
c = 2;
}
c += 1;
console.log(`c = ${c}`);This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Type Coercion7Bill Split Calculator
Welcome MessageCalculating The Tip And Total2Variables
NumbersStringBooleanNaming ConventionsEmpty VariablesRecap - Initialize VariablesConstants3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsStrict vs Loose EqualityRecap - Simple Math6Basic IO
OutputOutput with VariablesType Conversion - Part 1Type Conversion - Part 2Recap - Till 120Recap - True or False