Back

Activity 2.4 Nesting Code Blocks

divider

Introduction

Activity 2.4

Nesting Code Blocks

Topics

  • Nesting Code Blocks: Building Complex Logic
  • Demo: Confirm Account Deletion
  • Importance of Code Formatting

Nesting Code Blocks: Building Complex Logic

Nesting is the process of placing one set of instructions (a code block) inside another.

This technique is crucial for making decisions based on previous selections, which is common in even basic programs.

Demo: Confirm Account Deletion

let answer = prompt("Would you like to delete your account?");
if (answer == "yes") {
let confirm = prompt("Are you ABSOLUTELY SURE?");
if (confirm == "yes") {
console.log("Deleting your account.");
}
else {
console.log("Cancelling your request.");
}
}

The inner block of code only executes if the condition for the outer block is first met.

Demo: Confirm Account Deletion

let answer = prompt("Would you like to delete your account?");
if (answer == "yes") {
let confirm = prompt("Are you ABSOLUTELY SURE?");
if (confirm == "yes") {
console.log("Deleting your account.");
}
else {
console.log("Cancelling your request.");
}
}

Would you like to delete your account? yes [Enter]
Are you ABSOLUTELY SURE? yes [Enter]
Deleting your account.

Importance of Code Formatting

It's crucial to keep your code nicely formatted. Good formatting makes code easier to read, understand, and debug.

1. Indentation: Always indent one tab for every code block. If you have a nested block, the code in the nested block should be indented again. This visually shows the level of nesting.

2. Grouping Statements: if, else if, and else statements that belong together should not have space between them. Group them together to visually indicate that they are related.

Importance of Code Formatting

3. Spacing Sections: Space your code based on logical sections. Avoid bunching up your entire program; this makes it much easier to read and isolate issues when debugging.

'F' → Fullscreen

Objectives

  • icon Nesting if statements
  • icon Testing nested branching statements
divider

Activity Tasks

  • icon Create a new project named 2-4-nesting.js.
  • icon Complete each task individually.

Task 1: Initialize Data

  • icon Initialize the variables for the game.
    • icon The two ending variables are initialized to false. If the use survives one of the scenarios, the variable is changed to true, which will be used to select an ending.
    • icon The player can pick up items an accumulate gold.
2-4-nesting.js
// If the player beats one of the levels, set its boolean variable to true
let wolfpackEnding = false;
let dragonEnding = false;
let gold = 0;
let twinkies = 0;

Task 2: Prologue

2-4-nesting.js
5 collapsed lines
// If the player beats one of the levels, set its boolean variable to true
let wolfpackEnding = false;
let dragonEnding = false;
let gold = 0;
let twinkies = 0;
// Prologue -----------------------------------------------------------------------------
console.log("Your car crashes into a tree during a thunderstorm in the woods.");
console.log("Darkness surrounds you as thunder crashes and rain pours.");
console.log("You spot a cave nearby, dimly lit by flashes of lightning, and run towards it for shelter.");
console.log("Inside, you see two shadowy paths diverging deeper into the unknown...\n");
// Convert a string to lowercase using String.toLowerCase()
let path = prompt("Which path do you take? (left or right) ->").toLowerCase();
if (path == "left" || path == "right") {
console.log("\nAs you move forward, you see something glimmering on the ground — a Hostess Twinkie.");
console.log("Do you eat the Twinkie for sustenance, or will you save it for later?");
let twinkieChoice = prompt("(take or eat) ->").toLowerCase();
if (twinkieChoice == "take") {
console.log("You slip the Twinkie into your pocket, unsure what awaits in the darkness...\n");
twinkies = twinkies + 1;
}
else if (twinkieChoice == "eat") {
console.log("Feeling uneasy, you eat the Twinkie to keep up your strength.\n");
}
else {
console.log("You leave the Twinkie untouched, feeling an ominous presence watching.\n");
}
}
//

Task 3: Construct Selection Statements for Main Levels

  • icon Each code block will be completed individually. Take care to keep track of what section you are working on.
2-4-nesting.js
32 collapsed lines
// If the player beats one of the levels, set its boolean variable to true
let wolfpackEnding = false;
let dragonEnding = false;
let gold = 0;
let twinkies = 0;
// Prologue -----------------------------------------------------------------------------
console.log("Your car crashes into a tree during a thunderstorm in the woods.");
console.log("Darkness surrounds you as thunder crashes and rain pours.");
console.log("You spot a cave nearby, dimly lit by flashes of lightning, and run towards it for shelter.");
console.log("Inside, you see two shadowy paths diverging deeper into the unknown...\n");
// Convert a string to lowercase using String.toLowerCase()
let path = prompt("Which path do you take? (left or right) ->").toLowerCase();
if (path == "left" || path == "right") {
console.log("\nAs you move forward, you see something glimmering on the ground — a Hostess Twinkie.");
console.log("Do you eat the Twinkie for sustenance, or will you save it for later?");
let twinkieChoice = prompt("(take or eat) ->").toLowerCase();
if (twinkieChoice == "take") {
console.log("You slip the Twinkie into your pocket, unsure what awaits in the darkness...\n");
twinkies = twinkies + 1;
}
else if (twinkieChoice == "eat") {
console.log("Feeling uneasy, you eat the Twinkie to keep up your strength.\n");
}
else {
console.log("You leave the Twinkie untouched, feeling an ominous presence watching.\n");
}
}
// Caves -----------------------------------------------------------------------------
// Left -> Wolfpack
// Right -> Dragon
// Else -> No path chosen
if (path == "left") {
}
else if (path == "right") {
}
else {
}
//

Task 4: Wolfpack Level

2-4-nesting.js
32 collapsed lines
// If the player beats one of the levels, set its boolean variable to true
let wolfpackEnding = false;
let dragonEnding = false;
let gold = 0;
let twinkies = 0;
// Prologue -----------------------------------------------------------------------------
console.log("Your car crashes into a tree during a thunderstorm in the woods.");
console.log("Darkness surrounds you as thunder crashes and rain pours.");
console.log("You spot a cave nearby, dimly lit by flashes of lightning, and run towards it for shelter.");
console.log("Inside, you see two shadowy paths diverging deeper into the unknown...\n");
// Convert a string to lowercase using String.toLowerCase()
let path = prompt("Which path do you take? (left or right) ->").toLowerCase();
if (path == "left" || path == "right") {
console.log("\nAs you move forward, you see something glimmering on the ground — a Hostess Twinkie.");
console.log("Do you eat the Twinkie for sustenance, or will you save it for later?");
let twinkieChoice = prompt("(take or eat) ->").toLowerCase();
if (twinkieChoice == "take") {
console.log("You slip the Twinkie into your pocket, unsure what awaits in the darkness...\n");
twinkies = twinkies + 1;
}
else if (twinkieChoice == "eat") {
console.log("Feeling uneasy, you eat the Twinkie to keep up your strength.\n");
}
else {
console.log("You leave the Twinkie untouched, feeling an ominous presence watching.\n");
}
}
// Caves -----------------------------------------------------------------------------
// Left -> Wolfpack
// Right -> Dragon
// Else -> No path chosen
if (path == "left") {
console.log("You cautiously take the left path.");
console.log("A few steps in, you freeze as the piercing eyes of a pack of wolves emerge from the shadows.");
console.log("The pack leader, larger and fiercer than the others, steps forward, growling softly...\n");
let wolfChoice = prompt("Do you offer the pack leader your hand in peace? (yes or no) ->").toLowerCase();
if (wolfChoice == "yes" && twinkies >= 1) {
console.log("As you reach out, the wolves smell the Twinkie...");
console.log("In a frenzy of hunger, they turn on you, and you're surrounded with no escape!\n");
}
else if (wolfChoice == "yes") {
console.log("The pack leader sniffs your hand and accepts you into the fold.");
console.log("You're given a small satchel of gold as a token of their trust.");
console.log("You settle in with the wolves, awaiting dawn as the storm howls outside...\n");
gold = gold + 5;
wolfpackEnding = true;
}
else {
console.log("Sensing your hesitation, the wolves close in, their teeth bared.");
console.log("You feel their claws sink in, and everything goes black...\n");
}
}
else if (path == "right") {
}
else {
}
//

Task 5: Dragon Level

  • icon Warning! Take your time with this section. There are multiple levels of nested blocks.
2-4-nesting.js
32 collapsed lines
// If the player beats one of the levels, set its boolean variable to true
let wolfpackEnding = false;
let dragonEnding = false;
let gold = 0;
let twinkies = 0;
// Prologue -----------------------------------------------------------------------------
console.log("Your car crashes into a tree during a thunderstorm in the woods.");
console.log("Darkness surrounds you as thunder crashes and rain pours.");
console.log("You spot a cave nearby, dimly lit by flashes of lightning, and run towards it for shelter.");
console.log("Inside, you see two shadowy paths diverging deeper into the unknown...\n");
// Convert a string to lowercase using String.toLowerCase()
let path = prompt("Which path do you take? (left or right) ->").toLowerCase();
if (path == "left" || path == "right") {
console.log("\nAs you move forward, you see something glimmering on the ground — a Hostess Twinkie.");
console.log("Do you eat the Twinkie for sustenance, or will you save it for later?");
let twinkieChoice = prompt("(take or eat) ->").toLowerCase();
if (twinkieChoice == "take") {
console.log("You slip the Twinkie into your pocket, unsure what awaits in the darkness...\n");
twinkies = twinkies + 1;
}
else if (twinkieChoice == "eat") {
console.log("Feeling uneasy, you eat the Twinkie to keep up your strength.\n");
}
else {
console.log("You leave the Twinkie untouched, feeling an ominous presence watching.\n");
}
}
// Caves -----------------------------------------------------------------------------
// Left -> Wolfpack
// Right -> Dragon
// Else -> No path chosen
if (path == "left") {
21 collapsed lines
console.log("You cautiously take the left path.");
console.log("A few steps in, you freeze as the piercing eyes of a pack of wolves emerge from the shadows.");
console.log("The pack leader, larger and fiercer than the others, steps forward, growling softly...\n");
let wolfChoice = prompt("Do you offer the pack leader your hand in peace? (yes or no) ->").toLowerCase();
if (wolfChoice == "yes" && twinkies >= 1) {
console.log("As you reach out, the wolves smell the Twinkie...");
console.log("In a frenzy of hunger, they turn on you, and you're surrounded with no escape!\n");
}
else if (wolfChoice == "yes") {
console.log("The pack leader sniffs your hand and accepts you into the fold.");
console.log("You're given a small satchel of gold as a token of their trust.");
console.log("You settle in with the wolves, awaiting dawn as the storm howls outside...\n");
gold = gold + 5;
wolfpackEnding = true;
}
else {
console.log("Sensing your hesitation, the wolves close in, their teeth bared.");
console.log("You feel their claws sink in, and everything goes black...\n");
}
}
else if (path == "right") {
console.log("You take the right path, deeper into the damp, dark cave.");
console.log("Suddenly, a rotten, smoky smell fills the air. A massive dragon with dull, greedy eyes looms in the shadows.");
console.log("The dragon sniffs the air and sneers, 'Did you bring me something sweet?'");
let dragonChoice = prompt("Do you offer him a treat? (yes or no) ->").toLowerCase();
if (dragonChoice == "yes" && twinkies >= 1) {
console.log("The dragon's eyes widen as he devours the Twinkie. 'Delicious!' he roars.");
console.log("In gratitude, he hands you a pile of gold coins.\n");
let goldChoice = prompt("How much gold do you take? ->");
let goldAmount = parseInt(goldChoice);
if (goldAmount > 0 && goldAmount <= 100) {
console.log("The dragon grunts approval, allowing you to take the gold...\n");
gold = gold + goldAmount;
}
else if (goldAmount > 100) {
console.log("The dragon's eyes narrow, and he hisses, 'Greed will get you nothing.'\n");
}
else {
// This handles 0, negative numbers, or non-numeric input (NaN)
// where parseInt fails, mirroring the original JavaScript 'else' logic.
console.log("The dragon, impressed by your modesty, lets you take all the gold!\n");
gold = gold + 100000;
}
dragonEnding = true;
}
else {
console.log("The dragon's face darkens, and he lunges towards you!");
console.log("His jaws close around you as everything fades to black...\n");
}
}
else {
}
//

Task 6: Default Bad Ending

  • icon This block will execute if neither 'left' nor 'right' is chosen.
2-4-nesting.js
32 collapsed lines
// If the player beats one of the levels, set its boolean variable to true
let wolfpackEnding = false;
let dragonEnding = false;
let gold = 0;
let twinkies = 0;
// Prologue -----------------------------------------------------------------------------
console.log("Your car crashes into a tree during a thunderstorm in the woods.");
console.log("Darkness surrounds you as thunder crashes and rain pours.");
console.log("You spot a cave nearby, dimly lit by flashes of lightning, and run towards it for shelter.");
console.log("Inside, you see two shadowy paths diverging deeper into the unknown...\n");
// Convert a string to lowercase using String.toLowerCase()
let path = prompt("Which path do you take? (left or right) ->").toLowerCase();
if (path == "left" || path == "right") {
console.log("\nAs you move forward, you see something glimmering on the ground — a Hostess Twinkie.");
console.log("Do you eat the Twinkie for sustenance, or will you save it for later?");
let twinkieChoice = prompt("(take or eat) ->").toLowerCase();
if (twinkieChoice == "take") {
console.log("You slip the Twinkie into your pocket, unsure what awaits in the darkness...\n");
twinkies = twinkies + 1;
}
else if (twinkieChoice == "eat") {
console.log("Feeling uneasy, you eat the Twinkie to keep up your strength.\n");
}
else {
console.log("You leave the Twinkie untouched, feeling an ominous presence watching.\n");
}
}
// Caves -----------------------------------------------------------------------------
// Left -> Wolfpack
// Right -> Dragon
// Else -> No path chosen
if (path == "left") {
21 collapsed lines
console.log("You cautiously take the left path.");
console.log("A few steps in, you freeze as the piercing eyes of a pack of wolves emerge from the shadows.");
console.log("The pack leader, larger and fiercer than the others, steps forward, growling softly...\n");
let wolfChoice = prompt("Do you offer the pack leader your hand in peace? (yes or no) ->").toLowerCase();
if (wolfChoice == "yes" && twinkies >= 1) {
console.log("As you reach out, the wolves smell the Twinkie...");
console.log("In a frenzy of hunger, they turn on you, and you're surrounded with no escape!\n");
}
else if (wolfChoice == "yes") {
console.log("The pack leader sniffs your hand and accepts you into the fold.");
console.log("You're given a small satchel of gold as a token of their trust.");
console.log("You settle in with the wolves, awaiting dawn as the storm howls outside...\n");
gold = gold + 5;
wolfpackEnding = true;
}
else {
console.log("Sensing your hesitation, the wolves close in, their teeth bared.");
console.log("You feel their claws sink in, and everything goes black...\n");
}
}
else if (path == "right") {
33 collapsed lines
console.log("You take the right path, deeper into the damp, dark cave.");
console.log("Suddenly, a rotten, smoky smell fills the air. A massive dragon with dull, greedy eyes looms in the shadows.");
console.log("The dragon sniffs the air and sneers, 'Did you bring me something sweet?'");
let dragonChoice = prompt("Do you offer him a treat? (yes or no) ->").toLowerCase();
if (dragonChoice == "yes" && twinkies >= 1) {
console.log("The dragon's eyes widen as he devours the Twinkie. 'Delicious!' he roars.");
console.log("In gratitude, he hands you a pile of gold coins.\n");
let goldChoice = prompt("How much gold do you take? ->");
let goldAmount = parseInt(goldChoice);
if (goldAmount > 0 && goldAmount <= 100) {
console.log("The dragon grunts approval, allowing you to take the gold...\n");
gold = gold + goldAmount;
}
else if (goldAmount > 100) {
console.log("The dragon's eyes narrow, and he hisses, 'Greed will get you nothing.'\n");
}
else {
// This handles 0, negative numbers, or non-numeric input (NaN)
// where parseInt fails, mirroring the original Python 'else' logic.
console.log("The dragon, impressed by your modesty, lets you take all the gold!\n");
gold = gold + 100000;
}
dragonEnding = true;
}
else {
console.log("The dragon's face darkens, and he lunges towards you!");
console.log("His jaws close around you as everything fades to black...\n");
}
}
else {
console.log("You hesitate, feeling the storm grow stronger as lightning flashes around you.");
console.log("Suddenly, a bolt strikes nearby, and you fall to the ground, darkness closing in.\n");
}
//

Task 7: Epilogue

  • icon Note the win conditions.
2-4-nesting.js
99 collapsed lines
// If the player beats one of the levels, set its boolean variable to true
let wolfpackEnding = false;
let dragonEnding = false;
let gold = 0;
let twinkies = 0;
// Prologue -----------------------------------------------------------------------------
console.log("Your car crashes into a tree during a thunderstorm in the woods.");
console.log("Darkness surrounds you as thunder crashes and rain pours.");
console.log("You spot a cave nearby, dimly lit by flashes of lightning, and run towards it for shelter.");
console.log("Inside, you see two shadowy paths diverging deeper into the unknown...\n");
// Convert a string to lowercase using String.toLowerCase()
let path = prompt("Which path do you take? (left or right) ->").toLowerCase();
if (path == "left" || path == "right") {
console.log("\nAs you move forward, you see something glimmering on the ground — a Hostess Twinkie.");
console.log("Do you eat the Twinkie for sustenance, or will you save it for later?");
let twinkieChoice = prompt("(take or eat) ->").toLowerCase();
if (twinkieChoice == "take") {
console.log("You slip the Twinkie into your pocket, unsure what awaits in the darkness...\n");
twinkies = twinkies + 1;
}
else if (twinkieChoice == "eat") {
console.log("Feeling uneasy, you eat the Twinkie to keep up your strength.\n");
}
else {
console.log("You leave the Twinkie untouched, feeling an ominous presence watching.\n");
}
}
// Caves -----------------------------------------------------------------------------
// Left -> Wolfpack
// Right -> Dragon
// Else -> No path chosen
if (path == "left") {
console.log("You cautiously take the left path.");
console.log("A few steps in, you freeze as the piercing eyes of a pack of wolves emerge from the shadows.");
console.log("The pack leader, larger and fiercer than the others, steps forward, growling softly...\n");
let wolfChoice = prompt("Do you offer the pack leader your hand in peace? (yes or no) ->").toLowerCase();
if (wolfChoice == "yes" && twinkies >= 1) {
console.log("As you reach out, the wolves smell the Twinkie...");
console.log("In a frenzy of hunger, they turn on you, and you're surrounded with no escape!\n");
}
else if (wolfChoice == "yes") {
console.log("The pack leader sniffs your hand and accepts you into the fold.");
console.log("You're given a small satchel of gold as a token of their trust.");
console.log("You settle in with the wolves, awaiting dawn as the storm howls outside...\n");
gold = gold + 5;
wolfpackEnding = true;
}
else {
console.log("Sensing your hesitation, the wolves close in, their teeth bared.");
console.log("You feel their claws sink in, and everything goes black...\n");
}
}
else if (path == "right") {
console.log("You take the right path, deeper into the damp, dark cave.");
console.log("Suddenly, a rotten, smoky smell fills the air. A massive dragon with dull, greedy eyes looms in the shadows.");
console.log("The dragon sniffs the air and sneers, 'Did you bring me something sweet?'");
let dragonChoice = prompt("Do you offer him a treat? (yes or no) ->").toLowerCase();
if (dragonChoice == "yes" && twinkies >= 1) {
console.log("The dragon's eyes widen as he devours the Twinkie. 'Delicious!' he roars.");
console.log("In gratitude, he hands you a pile of gold coins.\n");
let goldChoice = prompt("How much gold do you take? ->");
let goldAmount = parseInt(goldChoice);
if (goldAmount > 0 && goldAmount <= 100) {
console.log("The dragon grunts approval, allowing you to take the gold...\n");
gold = gold + goldAmount;
}
else if (goldAmount > 100) {
console.log("The dragon's eyes narrow, and he hisses, 'Greed will get you nothing.'\n");
}
else {
// This handles 0, negative numbers, or non-numeric input (NaN)
// where parseInt fails, mirroring the original JavaScript 'else' logic.
console.log("The dragon, impressed by your modesty, lets you take all the gold!\n");
gold = gold + 100000;
}
dragonEnding = true;
}
else {
console.log("The dragon's face darkens, and he lunges towards you!");
console.log("His jaws close around you as everything fades to black...\n");
}
}
else {
console.log("You hesitate, feeling the storm grow stronger as lightning flashes around you.");
console.log("Suddenly, a bolt strikes nearby, and you fall to the ground, darkness closing in.\n");
}
// Epilogue -----------------------------------------------------------------------------
console.log("-- Ending --");
if (wolfpackEnding) {
console.log("By cuddling with the wolfpack, you weather out the storm.");
console.log("Upon leaving the cave, they follow you, seeing you as the new pack leader.");
console.log("You survived!!!");
}
else if (dragonEnding) {
console.log("By tempting the dragon with a delicious Hostess snack cake, you avoid his wrath.");
console.log("He flies you back home after the storm, but not after raiding the nearest Hostess factory.");
console.log("You survived!!!");
}
else {
console.log("Game Over!");
}
if (gold > 0) {
console.log(`\nYou not only survived, but you found ${gold} gold!`);
}
//
divider

Sample Output

Your program output should something similar to the sample output below.

Sample Output
Your car crashes into a tree during a thunderstorm in the woods.
Darkness surrounds you as thunder crashes and rain pours.
You spot a cave nearby, dimly lit by flashes of lightning, and run towards it for shelter.
Inside, you see two shadowy paths diverging deeper into the unknown...
Which path do you take? (left or right) -> left
As you move forward, you see something glimmering on the ground - a Hostess Twinkie.
Do you eat the Twinkie for sustenance, or will you save it for later?
(take or eat) -> take
You slip the Twinkie into your pocket, unsure what awaits in the darkness...
You cautiously take the left path.
A few steps in, you freeze as the piercing eyes of a pack of wolves emerge from the shadows.
The pack leader, larger and fiercer than the others, steps forward, growling softly...
Do you offer the pack leader your hand in peace? (yes or no) -> yes
As you reach out, the wolves smell the Twinkie...
In a frenzy of hunger, they turn on you, and you're surrounded with no escape!
-- Ending --
Game Over!
divider

Reflection Questions

You may write your reflection answers as comments at the bottom of your code.

  1. The lesson stressed the importance of indentation and spacing sections. In the Dungeon Crawler, you ended up with several layers of nested if/else blocks. If you had not kept your code perfectly formatted, what's a debugging mistake you may have made when writing the wolfpack or dragon sections?
divider

Submission

Submit your activity and reflection answers to the appropriate dropbox.

Activity Complete