I have the following function:
function generateTimeStamp(currentDate = null) {
if (!currentDate) {
let hours = Math.round(1+(23*Math.random()));
console.log('hours is ' + hours.toString());
} else {
let hours = currentDate.getHours();
}
if (hours < 10) {hours = "0" + hours;}
return hours;
As you can see, I define the variable hours in a way or the other depending on the fact that the parameter currentDate is (or not) null, but I define it in any case.
If you see inside the first if block, the console.log() logs me correctly the value of the variable hours.
However, right after (when I try to perform the last instruction before return), I get an exception saying hours is not defined.
- Why does the variable
hoursloses its value outside the if block? - How can I fix my issue?
Here a JSFiddle to play around.