2.14 The "switch" statement

히진로그·2022년 2월 3일
0

Modern-Javascript

목록 보기
11/14

출처: https://javascript.info/

  • 혼자 읽고 타이핑하며 이해하면서 공부한 흔적 남기기

A switch statement can replace multiple if checks.

The syntax

The switch has one or more case blocks and an optional default.

switch(x) {
	case 'value1': // if ( x === 'value1')
		...
		[break]
	case 'value2': // if ( x === 'value2')
		...
		[break]
	default:
		...
		[break]
}
  • The value of x is checked for strict equality to the value from the first case(that is, value1) then to the second (value2) and so on.
  • If the equality is found, switch starts to execute the code starting from the corresponding case, until the nearest break(or until the end of switch).

→ If there is no break then the execution continues with the next case without any checks.

  • If no case is matched then the default code is executed (if it exists).

Grouping of "case"

Several variants of case which share the same code can be grouped.

Type matters

equality check는 항상 strict이다. value는 match하기 위해 항상 같은 타입이어야 한다.

Task

// 1
let a = prompt("Please enter a number");
console.log(a);
typeof(a);
console.log(`typeof: ${typeof(a)}`)

// 2
let a = +prompt("Please enter a number");
console.log(a);
typeof(a);
console.log(`typeof: ${typeof(a)}`)
  1. type: string
  2. type: number

→ before prompt add '+' that converts value from string to number

0개의 댓글