β†ͺ️ Conditionals

Published Jul 23, 2021Updated Sep 9, 2021
Contribute to Docs

Conditionals take an expression, which is code that evaluates to determine a value, and checks if it is πŸ‘ or πŸ‘Ž. If it’s πŸ‘, we can tell our program to do one thing β€” we can even account for πŸ‘Ž to do another.

As we write more complex programs, conditionals allow us to address multiple scenarios and make our programs more robust.

If Statement

The β†ͺ️ statement is very important. It allows for conditional execution of a code block. The whole syntax is:

  • If the condition evaluates to πŸ‘, the code block will be executed.
  • And if it evaluates to πŸ‘Ž, it’ll be ignored.

This example will display β€œa is greater than b” if the content for variable a is greater than b:

β†ͺ️ a ▢️ b πŸ‡
πŸ˜€ πŸ”€a is greater than bπŸ”€β—οΈ
πŸ‰

Else Statement

The πŸ™… extends an β†ͺ️ statement to execute an additional code block in case the expression in the if statement evaluates to false.

For example, the following code would display β€œa is greater than b” if a is greater than b, and a is not greater than b otherwise:

β†ͺ️ a ▢️ b πŸ‡
πŸ˜€ πŸ”€a is greater than bπŸ”€β—οΈ
πŸ‰
πŸ™… πŸ‡
πŸ˜€ πŸ”€a is not greater than bπŸ”€β—οΈ
πŸ‰

Note: The πŸ™… statements is only executed if the β†ͺ️ statement evaluated to πŸ‘Ž, and if all πŸ™…β†ͺ️ statements evaluated to πŸ‘Ž too.

All contributors

Looking to contribute?

Learn Emojicode on Codecademy