1
function formatToStandardizedDate(from, to){

    const from_date = moment(from);

    if(to){
        let to_date = moment(to);
    }else{
        let to_date = null;
    }
}

console.log(formatToStandardizedDate("2017-04-19 00:00:00",null))

What's wrong with my code above? if to is null it at least assign a null to to_date but I got error of to_date of undefined error. Why?

Alex Yong
  • 7,425
  • 8
  • 24
  • 41

1 Answers1

6

You can't use same variable names with let keyword. It will throw errors if you try to do this.


Instead you have to use ternary operator:

let to_date = to ? moment(to) : null;

or declare it once above in the function and update the variable

function formatToStandardizedDate(from, to){
    const from_date = moment(from);
    let to_date = null; // initialize the variable with null
    if(to)
      to_date = moment(to); // <---here update the variable with new value.
}

Updated as per JaredSmith's comment and that seems good.

Jai
  • 74,255
  • 12
  • 74
  • 103