https://www.boostcourse.org/cs124/lecture/194611?isDesc=false
자바스크립트의 시작
부스트코스 무료 강의
www.boostcourse.org
[부스트코스-자바스크립트의 시작] 강의에서 배운 내용 복습
리팩토링 - 비효율적인 코드를 효율적으로 만들어 가독성을 높이고 유지보수를 쉽게 만드는 방법
document.querySelector('#night_day').value === 'night'
이 코드를
this.value === 'night'
로 간단하게 줄일 수 있다.
반복하여 쓰일 내용은 변수를 사용하여 중복되는 내용, 코드의 길이를 줄여 간단하게 한다.
또한 코드를 수정해야 할 때, 변수를 이용하지 않으면 코드 하나하나를 일일이 고쳐야 하지만, 변수를 이용하면 변수의 내용만 고치면 되기 때문에 수정이 쉽다.
코딩을 할 때에는 중복을 없애는 것이 중요
if(this.value === 'night') {
document.querySelector('body').style.backgroundColor = 'black';
document.querySelector('body').style.color = 'white';
this.value = 'day';
}
else {
document.querySelector('body').style.backgroundColor = 'white';
document.querySelector('body').style.color = 'black';
this.value = 'night';
}
var target = document.querySelector('body');
if(this.value === 'night') {
target.style.backgroundColor = 'black';
target.style.color = 'white';
this.value = 'day';
}
else {
target.style.backgroundColor = 'white';
target.style.color = 'black';
this.value = 'night';
}
반복되는 document.querySelector('body')를
var target = document.querySelector('body')로 target이라는 변수를 지정해 준다.
훨씬 코드가 단순해진 것을 볼 수 있다.
| [자바스크립트/javascript] reduce() (0) | 2023.01.18 |
|---|---|
| [자바스크립트/javascript] map() (0) | 2023.01.17 |
| [자바스크립트/javascript] filter() (0) | 2023.01.16 |
| [자바스크립트/javascript] 오류(error) 처리하기 (0) | 2023.01.16 |
| [자바스크립트/javascript] 객체 (0) | 2022.11.12 |