Is there something wrong with my code?


#1

https://www.codecademy.com/en/courses/learn-javascript/lessons/control-flow/exercises/switch

let moonPhase = "yaya";

switch(moonPhase) {
  case 'full': {
  	console.log('Howl!');
  	break;
    
  case 'mostly full': {
  	console.log('Arms and legs are getting hairier');
  	break;
    
  case 'mostly new': {
  	console.log('Back on two feet');
 		break;
    
 default:
 		console.log('Invalid moon phase');
    break;
}

#2

I definitely know it’s going to print default because of the value in the moonPhase, but it doesn’t do that either. The lesson allows to continue going. Is it me or there is a bug somewhere. If so where? Thanks you.


#3

Are we supposed to take you seriously if you butcher the lesson?


#4

Delete those opening curly brackets in:

case 'full': {   //<=== why opening curly bracket?

case 'mostly full': { //<=== why opening curly bracket?

case 'mostly new': {  //<=== why opening curly bracket?

Those opening curly brackets are unnecessary. Remove them, your code would work.

No, there’s no bug.

Cheers :slight_smile:


Edit: :rofl: @mtf


#5

Technically speaking, had they been properly closed at some point the code inside would be treated as a block with no syntax issues. A block with no conditional or binding executes as normal inline code. In this case, they would be anonymous blocks.


#6

Ah, I see. Just tested it. It would work if @rubyninja14762 decides to close it with closing brackets like:

case 'full': {
console.log(‘Howl!’);
break; 
};

case 'mostly full': {
console.log(‘Arms and legs are getting hairier’);
break; 
};

......

Good to know. Thanks @mtf ! :grinning:


#7

The anonymous blocks do still technically need a closing semicolon.

    };

#8

Edited, btw writing this way looks weird:

case 'full': {
console.log(‘Howl!’);
break;  };

this one looks nicer though:

case 'full': {
   console.log(‘Howl!’);
   break;  
};

Thanks for the reminder! :slight_smile:


#9

So long as you realize that the block notation is optional, and has no side effect. It does make the code readable, which is be the only consideration I would think viable.


#10

very helpful , thanks a lot


#11

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.