Control Structures: Conditionals and Loops

November 14, 2024

Control Structures: Conditionals and Loops

This post focuses on control structures in CoffeeScript, including conditionals (if statements) and loops (for and while). You’ll learn how to use these structures to control the flow of your programs effectively.

Understanding Conditionals

Conditionals allow you to execute different blocks of code based on certain conditions. In CoffeeScript, the syntax for an if statement is quite straightforward.

Basic If Statement

The basic structure of an if statement in CoffeeScript is as follows:

if condition
  # code to execute if condition is true

Here’s a simple example:

temperature = 30
if temperature > 25
  console.log 'It is hot!'

In this example, if the temperature is greater than 25, it will log ‘It is hot!’.

Else and Else If

You can also use else and else if to handle multiple conditions:

if temperature > 25
  console.log 'It is hot!'
else if temperature > 15
  console.log 'It is warm!'
else
  console.log 'It is cold!'

In this case, the program checks if the temperature is hot, warm, or cold and logs the appropriate message.

Switch Statements

CoffeeScript also supports switch statements for handling multiple conditions more elegantly:

fruit = 'apple'
switch fruit
  when 'banana'
    console.log 'This is a banana'
  when 'apple'
    console.log 'This is an apple'
  else
    console.log 'Unknown fruit'

In this example, the program checks the value of the fruit variable and logs a message based on its value.

Loops in CoffeeScript

Loops allow you to execute a block of code multiple times. CoffeeScript provides several looping constructs, including for loops and while loops.

For Loops

The for loop in CoffeeScript is quite powerful and can be used in various ways:

for number in [1..5]
  console.log number

This will log the numbers 1 through 5. The range syntax [1..5] creates an array of numbers from 1 to 5.

Iterating Over Arrays

You can also use for loops to iterate over arrays:

fruits = ['apple', 'banana', 'cherry']
for fruit in fruits
  console.log fruit

This code will log each fruit in the fruits array.

While Loops

While loops continue to execute as long as a specified condition is true:

count = 0
while count < 5
  console.log count
  count += 1

This will log the numbers 0 through 4, incrementing the count each time until it reaches 5.

Conclusion

Control structures are essential for directing the flow of your CoffeeScript programs. By mastering conditionals and loops, you can create more dynamic and responsive applications. In the next post, we will explore functions in CoffeeScript, which will further enhance your coding skills.