본문 바로가기

Javascript

JS 지저분한 코드 깨끗하게 바꾸는 팁!!

문제: 한 조건에 대한 답이 두 개일 때

 

 


기존

function check(a){

    if(typeof a === "string"){
        return console.log("맞아요")
    }else{

        return console.log("틀러요")

    }

}

해결 : 삼항 연산자 

 

function check(a){

    typeof a === "string"? console.log("맞아요") : console.log("틀려요") 

}

 

문제 :  예외 조건이 undefined || null 일 때 다른 메세지를 보내고 싶으면


기존

function printMessage(text){
	let message =text
	if(text === null || text === undefined){
	message="nothing to display"
	}

	console.log(message)

}

해결

 

function printMessage(text){
	//새로운 변수에 넣지만 만약에 undefined || null 이면 다른 값 출력


	let message = text ?? "nothing to display"
	console.log(message)

}