javascript - let variable is not defined - Stack Overflow

function formatToStandardizedDate(from, to){const from_date = moment(from);if(to){let to_date = moment(

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?

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?

Share Improve this question asked Apr 12, 2017 at 11:40 Alex YongAlex Yong 7,6558 gold badges27 silver badges42 bronze badges 4
  • 2 with let you can't use same names of var. – Jai Commented Apr 12, 2017 at 11:42
  • 1 Possible duplicate of What's the difference between using "let" and "var" to declare a variable? – mxr7350 Commented Apr 12, 2017 at 11:43
  • You'd need to define the let outside of the block if you want to use it outside the block. – Dave Newton Commented Apr 12, 2017 at 11:44
  • Where are you using to_date? – Satpal Commented Apr 12, 2017 at 11:44
Add a ment  | 

1 Answer 1

Reset to default 7

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 ment and that seems good.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744184435a4562137.html

相关推荐

  • javascript - let variable is not defined - Stack Overflow

    function formatToStandardizedDate(from, to){const from_date = moment(from);if(to){let to_date = moment(

    8天前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信