If / else statements
Conditional statements allow us to perform different actions based on different condition.
If / else statements
let name = "Lucas";
let status = "single";
if (status === "single") {
console.log(`${name} is single `);
}
- The conditions in javascript works in two steps, the first one is to check if the condition that you write is true or false and the second to execute the code.
- To write your condition after the
ifkeyword open()and write your code, the javascript engine will now check if your condition is true if it does then we can go to the second step. - So your condition is true so now we can execute the located inside the
{}.
let name = "Lucas";
let status = "married";
if (status === "single") {
console.log(`${name} is single `);
} else {
console.log(`${name} is married`);
}
- For this example we change the value of our
statusvariable and add a else condition. - So now our condition is now equal to false it means that we can't execute the code inside the first
{}so the javascript engine will execute the second line which iselse. - With else you can't add condition it means that if the if condition is false the code will always execute the else condition. we'll see now how to check many conditions.
If / else if / else statement
let name = "Lucas";
let status = "married";
if (status === "single") {
console.log(`${name} is single `);
} else if (name === "Lucas") {
console.log(`Your name is ${name}`);
} else {
console.log(`${name} is married`);
}
- We saw above how to check one condition but let's see now how to check many conditions.
- We use a new keywords here
else ifwho allow us to check another condition so right here if the firstifcondition is false the js engine will check if theelse ifcondition is true if it does then it will execute the code, if the condition is false it will execute theelsecondition. - In this example we used only one
else ifcondition but you can add as much as you wantelse ifcondition.
Current errors
This is a list of the main errors that you can meet:
Note: I'm not a wizard there is maybe some issue that you notice above so fell free to open an issue in the github repo if you find a new error not mentioned above.