• 카테고리

    질문 & 답변
  • 세부 분야

    프로그래밍 언어

  • 해결 여부

    해결됨

함수리턴강의 질문

22.12.20 16:05 작성 22.12.20 16:08 수정 조회수 189

1

const counterMaker = function () {
        const targetDateInput = dateFormMaker();
        const nowDate = new Date();
        const targetDate = new Date(targetDateInput).setHours(0, 0, 0, 0);   

위 함수에서 dateFormMaker()의 리턴값을

const targetDateInput 로 선언해서 targetDate 를

new Date(targetDateInput)로 선언해주셨는데

이 경우

new Date(dateFormMaker())처럼 리턴값을 바로 이용하는것 과 다른점이 무엇인가요?

답변 1

답변을 작성해보세요.

1

otter님의 프로필

otter

2022.12.20

안녕하세요 흥불님! 좋은 질문 감사합니다!

우리가 작성하는 로직에서는 두가지 방식이 큰 차이를 보이지는 않습니다만, 엄밀히 말하자면 차이점은 존재합니다!

자바스크립트의 코드는 위에서부터 한줄씩 읽어 내려가며 실행됩니다.

따라서 강의에서 설명 드리는 방식은 counterMaker 함수가 실행되면, dateFormMaker 함수를 실행하고 targetDateInput에 값이 담기게 된 후, nowDate, targetDate에 차례대로 값이 담기도록 설명 드리고 있죠.

const dateFormMaker = function () {
  console.log('dateFormMaker called'); // console.log
  const inputYear = document.querySelector('#target-year-input').value;
  const inputMonth = document.querySelector('#target-month-input').value;
  const inputDate = document.querySelector('#target-date-input').value;

  const dateFormat = `${inputYear}-${inputMonth}-${inputDate}`;
  return dateFormat;
};

const countMaker = function () {
  console.log('A'); // console.log
  const targetDateInput = dateFormMaker();
  console.log('B'); // console.log
  const nowDate = new Date();
  const targetDate = new Date(targetDateInput);

// A => dateFormMaker called => B 순으로 출력

그렇다면 흥불님이 질문에 언급해 주신 방식은 어떨까요?
아마 dateFormMaker 함수의 실행 시점이 달라지게 되겠죠?
먼저 nowDate에 현재 날짜가 담기게 되고 new Date를 통해 targetDate에 담길 값을 생성하고자 할 때,
그때, dateFormMaker 함수가 실행되겠죠.

const dateFormMaker = function () {
  console.log('dateFormMaker called'); // console.log
  const inputYear = document.querySelector('#target-year-input').value;
  const inputMonth = document.querySelector('#target-month-input').value;
  const inputDate = document.querySelector('#target-date-input').value;

  const dateFormat = `${inputYear}-${inputMonth}-${inputDate}`;
  return dateFormat;
};

const countMaker = function () {
  console.log('A'); // console.log
  // const targetDateInput = dateFormMaker();
  console.log('B'); // console.log
  const nowDate = new Date();
  const targetDate = new Date(dateFormMaker());

// A => B => dateFormMaker called 순으로 출력

이렇듯 자바스크립트의 실행 관점에서 보자면 위와 같은 차이점이 발생하게 됩니다.

어떠한 방식이 더 낫다.라고 이야기하긴 어렵겠지만, 이러한 차이점이 존재한다는 것을 알고 코드를 작성하신다면 로직을 구성하는데 도움이 되리라 생각됩니다!

흥불님의 프로필

흥불

질문자

2022.12.20

감사합니다!