Skip to content

Flow and Debugging in the Browser

At the end of this class, you should be able to…

  • Utilize decisions and loops to implement branching and repetition in scripts.
  • Demonstrate how to access and use browser developer tools for debugging JavaScript.
  • Interpret console error messages to identify code issues.
  • Apply breakpoints and step-through code execution to isolate bugs.
  • Utilize the console for testing code snippets and exploring variable values.

The focus of this lesson is on basic implementation of control structures and using the debugger. If students are concerned that they are learning several control structures in one lesson when weeks are taken to cover these topics in another course, remind them that we will be using these structures every day moving forward, and they will get the exposur they need to fully understand them.

Students must read chapter 2 of JSFBP


Install dependencies and run the dev server

Section titled “Install dependencies and run the dev server”
  1. Extract the starter zip to lesson-04
  2. Move into the lesson-04/ directory:
Terminal window
cd lesson-04
  1. Install the necessary dependencies:
Terminal window
npm install

or

Terminal window
npm i
  1. Run the dev server with the dev script:
Terminal window
npm run dev
  1. Open the provided development server URL in your browser
  2. You should see the default render for the vite project.
  3. Use this as the base for today’s examples.

Complete the demo along with your instructor and then attempt the exercise prompts (see the Student TODO comments at the end of the main.js file).

const x = 5;
if (x > 0) {
console.log('x is positive');
}
if (x % 2 === 0) {
console.log('x is even');
} else {
console.log('x is odd');
}
if (x > 10) {
console.log('x is greater than 10');
} else if (x < 0) {
console.log('x is non-positive');
} else {
console.log('x is between 1 and 10');
}
let count = 3;
while (count > 0) {
console.log('Countdown:', count);
count = count - 1;
}
let i = 0;
do {
console.log('i is', i);
i++;
} while (i < 3);
for (let j = 0; j < 3; j++) {
console.log(`j = ${j}`);
}

This small snippet includes two intentional bugs for students to find and fix. Uncomment and correct each bug as part of the exercise. Use the DevTools to help find and correct the bugs.

// Snippet with bugs for debugging practice
const num = 10;
if (num < 5) {
console.log('num is greater than 5');
} else {
console.log('num is 5 or less');
}
let k = 0;
while (k < 3) {
k + 1;
console.log(k);
}

Once you’re done making your own custom updates to the project, stage your files, commit your work, and push to the remote repository.

  1. Open a terminal in VS Code
  2. Stage all updated and created files:
Terminal window
git add .
  1. Commit the changes:
Terminal window
git commit -m 'Lesson 04 Example'
  1. Push your changes to the remote workbook repository:
Terminal window
git push origin main