Skip to main content

Conditions & Loops

Conditions#

Conditional statements examine specified criteria, and act in one way if the criteria are met, or in another way if the criteria are not met.

The criteria is mandatory for all conditional statements except the "else" conditional statement. The "else" conditional statement does not accept any criteria.

The following are the variants of conditional statements:

if#

Validates given criterion and performs specified actions if the criterion is met. The "If" conditional statement can be followed by "else if" and "else" conditional statements(not mandatory). If the criterion is not met, the actions are skipped, and the program moves on to the next task.

Example:

hour = 15;greeting = "";if (hour < 18) {  greeting = "Good day";}log greeting;

else if#

The "else if" conditional statement is always preceded by an "if" conditional statement. It executes given statements when the preceding "if" conditional statement fails and the "else if" criterion is met. If the "else if" criterion is also not met, the actions are skipped, and the program moves on to the next task.

Example:

time = 9;greeting = "";if (time < 10) {  greeting = "Good morning";} else if (time < 20) {  greeting = "Good day";}log greeting;

else#

The "else" conditional statement is always preceded by an "if" or an "else if" conditional statement. It executes given statements when the preceding "if" and "else if" conditional statements fail. The "else" statement, if present, must always be the last in a set of conditional statements, i.e, it must not be followed by the "if" or the "else if" condition in that set of statements.

Example:

time = 12;greeting = "";if (time < 10) {  greeting = "Good morning";} else if (time < 20) {  greeting = "Good day";} else {  greeting = "Good evening";}
log greeting;

Loops#

Loops are used to repeatedly run a block of code - until a certain condition is met. When developers talk about iteration or iterating over, say, an array, it is the same as looping.

List Iteration#

The for each statement is used to iterate over the elements of the collection. The collection may be an array or a list. It executes for each element present in the array.

Example:

list = [1, 2, 3, 4, 5];
for each index, value in list {  log index;  log value;}

Map Iteration#

Map is a data structure which allows storing of [key, value] pairs where any value can be either used as a key or value. The iteration of elements in a map object is done in the insertion order and a for each loop returns key and value pairs for each iteration.

Example:

data = {};data.name = “user”:data.age = 30;data.exp = 5;
for each key, value in data {   log key;   log value;}