Study/JavaScript(Clean code)

    [JavaScript][clean-code] 클로저 (Closure)

    * Closure (클로저) [참고 내용] https://latte1114.tistory.com/298 https://latte1114.tistory.com/365 * 클로저 예시 코드 function add(num1) { return function sum(num2) { return num1 + num2; }; } const addOne = add(1); console.log(addOne(3)) // 4 // 1을 넘긴상태로 scope가 기억되기 때문에 4가 호출된다. 클로저를 사용한 함수를 보면 괄호가 2개이다. 괄호가 모두 호출되면 완벽히 함수가 다 호출되고 종료된다. 그말은 즉, 괄호를 한번 실행했기 때문에 add라는 함수는 외부함수만 실행이 된거고 실행된 상태에서 내부의 함수의 환경을 기억하고 ..

    [JavaScript][clean-code] 순수 함수(pure function)

    * 순수 함수(pure function) - 부작용(side effect)을 일으키지 않는 함수 * 부작용 (side effect) list Logging a value to the console Saving a file Setting an async timer Making an AJAX HTTP request Modifying some state that exists outside of a function, or mutating arguments to a function Generating random numbers or unique random IDs (such as Math.random() or Date.now()) * 순수 함수가 아닌 예시 (BAD) let num1 = 10; let num2 =..

    [JavaScript][clean-code] Callback Function

    * Callback Function - callback function을 이용한 함수 위임 * callback function 사용하기 전 // callback함수 사용전 function register() { const isConfirm = confirm( '회원가입에 성공했습니다.', ); if (isConfirm) { redirectUserInfoPage(); } } function login() { const isConfirm = confirm( '로그인에 성공했습니다.', ); if (isConfirm) { redirectIndexPage(); } } * callback function 사용후 // callback 사용후 function confirmModal(message, cbFunc) { ..

    [JavaScript][clean-code] 화살표 함수 (Arrow function)

    * 화살표 함수 (Arrow function) [참조 내용] https://latte1114.tistory.com/367 * 예시 코드 // arrow function const user = { name : 'Hyeonwoo', getName : () => { return this.name; }, }; user.getName(); // undefined // 일반 method const user = { name : 'Hyeonwoo', getName() { return this.name; }, }; user.getName(); // Hyeonwoo 화살표 함수로 this.name에 접근시 undefined가 반환된다. 일반 메서드로 this.name에 접근시 정상적으로 this.name의 값이 반환된다...

    [JavaScript][clean-code] void & return

    * void & return void : 함수의 반환이 없다. return : 함수가 무언가를 반환한다. * 예시로 보는 void와 return function handleClick() { return setState(false); } function showAlert(message) { return alert(message); } setState함수와 alert함수를 void함수이다. 따라서 함수의 반환이 존재하지않는다. 따라서 return을 넣어주지 않아도 된다. 굳이 반환이 없는데 return을 사용할 필요가 없다. undefined가 return된다. * JavaScript는 기본적으로 아무런 return이 없을때는 undefined를 return한다. function test(sum1, sum2..

    [JavaScript][clean-code] Rest Parameters

    * Rest Parameters [참조 내용] https://latte1114.tistory.com/297 * 예시 코드 function sumTotal() { return Array.from(arguments).reduce( (acc, curr) => acc + curr, ); } sumTotal(1, 2, 3, 4, 5, 6, 6); arguments를 활용하여 가변인자를 취한다. * 만약 추가적인 인자를 받고 싶은 경우에는?? - Rest parameters를 이용한다. function sumTotal(...args) { return args.reduce ( (acc, curr) => acc + curr, ); } sumTotal(1, 2, 3, 4, 5, 6, 6); [참고] rest parame..