GitHub Repository Submission

When using GitHub mode, paste your repository URL below and click Save URL to store it. The saved URL will be automatically included with every message you send until you choose to clear it. Learn more

Your GitHub repository URL is saved. LSBot will automatically fetch your latest code from this repository for each message. To change the URL, clear it first and save a new one.

Exercise 4

What does the following code log to the console, and why?

function barCodeScanner(serial) {
  switch (serial) {
    case '123':
      console.log('Product1');
    case '113':
      console.log('Product2');
    case '142':
      console.log('Product3');
    default:
      console.log('Product not found!');
  }
}

barCodeScanner('113');

Solution

The output is:

Product2
Product3
Product not found!

Since the case clauses of the switch statement lack break statements, control falls through from the matching case '113' clause and executes the code in the case '142' and default clauses as well. JavaScript doesn't care that the criteria for extra case clauses don't match our serial value. This fall-through behavior is often undesirable. To avoid it, you must add break statements to each case clause:

function barCodeScanner(serial) {
  switch (serial) {
    case '123':
      console.log('Product1');
      break;
    case '113':
      console.log('Product2');
      break;
    case '142':
      console.log('Product3');
      break;
    default:
      console.log('Product not found!');
  }
}

Video Walkthrough

Hi! I'm LSBot. I can help you think through the selected exercise by giving you hints and guidance without revealing the solution. Your code from the editor will be automatically detected. Want to know more? Refer to the LSBot User Guide .

Detected solution
Loading...

Submit your solution for LSBot review.

Hi! I'm LSBot. Your code from the editor will be automatically detected. I'll review your solution and provide feedback to help you improve. Ask questions about your solution or request a comprehensive code review. Want to know more? Refer to the LSBot User Guide .

Detected solution
Loading...