Web/Javascript

조건문 좀더 편하게 사용하기

망할고양이 2023. 1. 13. 11:08

조건문을 사용하다 보면 조건이 많을 때가 있습니다. 

if( 조건 || 조건 || 조건 .....)

이런 조건이 너무 많으면 가독성이 떨어지게 되고 반복되는 코드로 코드가 늘어지게 됩니다. 

예를 들면 아래와 같은 코드가 있습니다. 

function checkName(arg) {
	let rtn = false;
    if (arg === 'A' || arg === 'B' || arg === 'C' || arg === 'D' || arg === 'E' || arg === 'F'){
    	rtn = true;
    }
    return rtn;
  }

function testCode(){
	console.log(checkName('A')); // true
	console.log(checkName('ZZ')); // false
}

좀더 코드의 낭비가 없도록 작성해봅시다. 

function checkName(arg) {
	const = compareValue = ['A','B','C','D','E','F'];
	return compareValue.includes(arg);
  }

function testCode(){
	console.log(checkName('A')); // true
	console.log(checkName('ZZ')); // false
}