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?
- 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
1 Answer
Reset to default 7You 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
评论列表(0条)