I need help finding the problem to my JavaScript code. The code outputs ‘invalid day’ but instead It should be ‘open.
function workingHours(input) {
let hour = Number(input[0]);
let day = input[1];
if (day == "Monday" || day == "Tuesday" || day == "Wednesday" || day == "Thursday" || day == "Friday" || day == "Saturday") {
if (hour >= 10 && hour <= 18) {
console.log("open");
} else if (hour < 10 || hour >= 19) {
console.log("closed");
} else {
console.log("invalid hour");
}
} else if (day == "Sunday") {
if (hour <= 23 && hour >= 0) {
console.log("closed");
} else {
console.log("invalid hour");
}
} else {
console.log("invalid day");
}
}
workingHours("11", "Tuesday")
I tried making the input for ‘day’ all in lowercases and the required values in the ‘if’ also in lowercase but still didn’t work. I am new so I’m sorry if I am talking nonsense.
4
Answers
Your workingHours function takes 1 argument and you’re passing 2 arguments. Inside the function, you’re assuming that input would be an array but instead, you’re passing 2 separate arguments.
Make this change where you’re calling the function.
workingHours(["11", "Tuesday"])
In JS the parameters are coming into a function not as an array but as separate variables.
If you make the following change to the function params, the code works as you expect.
If you want to receive two different values, you can just use 2 parameters then you won’t need this part:
It would become to this:
I would recommend you to take a look on how functions work. On w3schools.com you can find a nice documentation: https://www.w3schools.com/js/js_functions.asp
I think the solution is really simple, how ever what you need is, you should know how you can debug your code. You can know more about it from here.
What is important here is that, for your example, if you have try to debug your code, then you will find out that
workingHours(input)
, has only one input.Potential way to check for what your below line is storing by, using
console.log()
. Output will Agrgument11
, will be store from their indexes which will make,hour
to have value1
andday
to contain value1
.Just FYR, you can do this also by putting
debugger
at start of function, to check how values forhour
andday
are passed.So, Once you find the root cause for your problem, you could try to think of different approach, which here is needed to have Arguments needs to be added to store day value and access them both directly.
You can visit this website for check outing some debugging tips.