149. Advanced Control Flow

변지영·2022년 1월 13일
0
post-thumbnail

Javascript Conditionals
if
else
else if
ternary operator
switch

ternary operator(삼항연산자)

conditon ? expr1 : expr2;

If condition is true, provide value(expr1)
If condition is false, provide value(expr2)

switch

Swith statements are really good for when you have a lot of conditions.
Instead of if else, if else, if else,,,,you can use switch statements.

function moveCommand(direction){
	var whatHappens;
	switch (direction) {
		case "forward":
			whatHappens ="you encounter a monster";
			break;
		case "back":
			whatHappens ="you arrived home";
			break;	
		case "right":
			whatHappens ="you found a river ";
			break;	
		case "left":
			whatHappens ="you run into a troll";
			break;	
		default:
		whatHappens = "please enter a valid direction";

	}
	return whatHappens;
}

"default" is if none of these conditions work and remember the program goes line by line.

"break": the program stops here and then goes straight out of the switch statement.


If I say break before whatHappens~, the program stops here and then goes straight out of the switch statement to return whatHappen.
So I get undifined.

0개의 댓글