✏️ Javascript

if문 중첩 줄이기

category
✏️ Javascript
date
thumbnail
slug
If문-중첩-줄이기
author
status
Public
tags
summary
type
Post

if문 중첩 제거 방법

  1. if문 다음에 나오는 공통된 절차를 각 분기점 내부에 넣는다.
  1. 분기점에서 짧은 절차부터 실행하게 if문을 작성한다.
  1. 짧은 절차가 끝나면 return(함수 내부의 경우)이나 break(for문 내부의 경우)로 중단한다.
  1. else를 제거한다.(이때 중첩 하나가 제거된다.)
  1. 다음 중첩된 분기점이 나오면 1~4의 과정을 반복한다.
 
const onClickNumber = (event) => {
  if (operator) { // operator가 있다.
    if (!numTwo) { // operator가 있는데 numTwo는 없다.
      $result.value = '';
    }
    // operator가 있다. (numTwo가 있다.)
    numTwo += event.target.textContent;
  } else {
    // 비어있다
    numOne += event.target.textContent;
  }
	// operator가 있거나 없거나
  $result.value += event.target.textContent;
};
해당 코드에 if문이 중첩되어 있다. 이를 줄여보자.
 
const onClickNumber = (event) => {
  if (!operator) { // operator가 없다.
    numOne += event.target.textContent;
    $result.value += event.target.textContent;
    return;
  }

  
  if (!numTwo) { // numTwo가 없다.
    $result.value = '';
  }
  numTwo += event.target.textContent;
  $result.value += event.target.textContent;
};
 
또 다른 예시
function test() {
	let result = '';
	if (a) {
		if (!b) {
			result = 'c';
		}
	} else {
		result = 'a';
	}
	result += 'b';
	return result;
}
 
 
  1. if문 다음에 나오는 공통된 절차를 각 분기점 내부에 넣는다.
    1. function test() {
      	let result = '';
      	if (a) {
      		if (!b) {
      			result = 'c';
      		}
      		result += 'b';
      		return result;
      	} else {
      		result = 'a';
      		result += 'b';
      		return result;
      	}
      }
       
  1. 분기점에서 짧은 절차부터 실행하게 if문을 작성한다.
    1. function test() {
      	let result = '';
      	if (!a) {
      		result = 'a';
      		result += 'b';
      		return result;
      	} else {
      		if (!b) {
      			result = 'c';
      		}
      		result += 'b';
      		return result;
      	}
      }
       
  1. 짧은 절차가 끝나면 return(함수 내부의 경우)이나 break(for문 내부의 경우)로 중단한다.
    1. function test() {
      	let result = '';
      	if (!a) {
      		result = 'a';
      		result += 'b';
      		return result;  // 원래 return이 있었음. 해당 과정에서 더 작업할 필요x
      	} else {
      		if (!b) {
      			result = 'c';
      		}
      		result += 'b';
      		return result;
      	}
      }
       
  1. else를 제거한다.(이때 중첩 하나가 제거된다.) ⇒ 중첩 제거 완료
    1. function test() {
      	let result = '';
      	if (!a) {
      		result = 'a';
      		result += 'b';
      		return result;
      	} 
      	if (!b) {
      		result = 'c';
      	}
      	result += 'b';
      	return result;
      }
 
 

참고

자바스크립트 강좌 4-4. if문 중첩 줄이기
조현영(zerocho)의 자바스크립트와 노드 프로그래밍 강좌 멤버십 가입: https://www.youtube.com/channel/UCp-vBtwvBmDiGqjvLjChaJw/join 다음 링크를 통해 강좌를 구매하시면 제가 인프런에서 부담하는 수수료의 33%가 면제됩니다. 아래 링크를 활용해주시면 감사하겠습니다! Node.js 교과서 - https://www.inflearn.com/course/노드-교과서?inst=ef3e5c11 Node.js 웹 크롤링 - https://www.inflearn.com/course/크롤링?inst=7f946bd9 React로 NodeBird SNS 만들기 - https://www.inflearn.com/course/노드버드-리액트-리뉴얼?inst=801ccd27 Vue로 NodeBird SNS 만들기 - https://www.inflearn.com/course/Vue-nodebird-sns?inst=2fd72dce Redux VS MobX (둘 다 배우자) - https://www.inflearn.com/course/redux-mobx-상태관리-도구?inst=de843706 웹 게임을 만들며 배우는 TypeScript - https://www.inflearn.com/course/웹게임을-만들며-배우는-typescript?inst=91d28742 웹 게임을 만들며 배우는 React에 TypeScript 적용하기 - https://www.inflearn.com/course/react-typescript-webgame?inst=1e5161e2 Node.js에 TypeScript 적용하기(feat. NodeBird) - https://www.inflearn.com/course/nodejs-typescript-적용?inst=941363ff -- 깃헙 -- https://github.com/zerocho (레포지토리 스타 눌러주세요) -- 후원 -- https://toon.at/donate/zerocho https://www.youtube.com/channel/UCp-vBtwvBmDiGqjvLjChaJw/join -- 소개 -- Node.js 교과서(길벗) 저자 제로초닷컴(ZeroCho.com) 운영자
자바스크립트 강좌 4-4. if문 중첩 줄이기