HTML Academy
A simple branch
Conditions2/17
Back to the list of tasks
  • 1. A simple branch
  • 2. Let’s use an alternative
  • 3. Simple comparisons
  • 4. Comparisons permitting equality
  • 5. Equality, inequality
  • 6. Strict string comparison
  • 7. Strict number comparison
  • 8. Condition-based actions
  • 9. If the condition is not fulfilled
  • 10. Values ​​as a condition
  • 11. Nested conditions
  • 12. Logical operators: &&, ||
  • 13. Logic traps
  • 14. Logical negation
  • 15. Let’s combine logical operators
  • 16. Summary of “Conditions”
  • 17. Second program: “How long should I walk?”
Simple comparisons
  • Sign up
  • Log in

Loading…
Everything will be ready in few seconds

  • Theory
  • Theory
  • Comments

Let’s use an alternative

The program perfectly shows when you can eat more, but does not report anything if Muffin has reached or exceeded his daily allowance. Because of this, Muffin nearly ate an extra 10 grams! You must remedy the situation.

Add a branch that runs when the condition is false. Use this pattern:

if (condition) {
  actions;
} else {
  other actions;
}

The “actions” branch runs if the condition is true. The “other actions” branch runs if the condition is false.

This is how we tell the program how to act in this or that situation. Such structures can be read as follows: if the condition is met, complete the action, otherwise complete other actions. In our case, the condition is as follows: if the amount of food eaten is less than the daily amount, then you can eat more, otherwise you cannot.

When all conditions of work are described, the program can work with real data from the boss. Let’s add the second branch of the condition to complete development of the “Can I Eat More?” program.

Comments

  • script.js
JavaScript
var foodInGrams = 60; var dayLimit = 80; if (foodInGrams < dayLimit) { console.log('You can eat more!'); }

What didn’t you like in this task?

Thanks! We’ll fix everything at once!

Console

The code has changed, click “Run” or turn autorun on.

Result

Goalscompleted

Add the else branch to the program:

  1. After the closing brace of the if block, add else { }.
  2. Inside the else block, add the console.log('Not a piece more!'); command.
  3. On the first line, replace the value of foodInGrams with muffin.ask('How many grams of food have you eaten today? Just be honest?').

Cookies ∙ Privacy ∙ License Agreement ∙ About ∙ Contacts ∙ © HTML Academy OÜ, 2019−2026

VISAMastercard

Log in

or

Forgot your password?

Sign up

Sign up

or
Log in

Restore access

Have you forgotten your password or lost access to your profile? Enter your email connected to your profile and we will send you a link to restore access.

Forgot to connect your email to the profile? Email us and we’ll help.