β†ͺ️ Conditionals

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.

Edit this page on GitHub

Contributors

Interested in helping build Docs? Read the Contribution Guide or share your feedback form.

Learn Emojicode on Codecademy

Edit this page on GitHub

Contributors