I am trying to build a traffic signal light.
there will be a variable called signal where green, yellow, and red are stored as a value of that variable. If the traffic light shows red light, that means there is danger. If the traffic light shows yellow light, I should stop. If there is a green light, I can cross the road.
My code is :
var signal = ["green", "yellow", "red"];
if (signal == "red") {
console.log("Danger");
}
else if (signal == "yellow") {
console.log("Stop");
}
else {
console.log("Cross the road");
}
I am expecting, if I select one color, then it will show the only output as I mentioned previously
2
Answers
You Code flow is not correct for solve your problem.
Array values are not required to check.
You simply check with if…else Condition.
Your variable
signal
has the value["green", "yellow", "red"]
and since you don’t change it ever, it can never be"red"
,"yellow"
or "green
". One is an array of strings, while the other is just a string.You are lacking a piece in your model, which is the current signal.
But that’s a bit hard to read, with indexing the array and stuff. And what if
currentSignal
is set to"teal"
? So let’s just refactor your signals into some sort of enumeration, or just a plain object:In a simple scenario this would now suffice, but technically you could still assign
currentSignal
a value of say …""
or"black"
, because javascript does not handle types very well, so you could (or should) add another condition:And of course, depending on your preferences you also use a switch statement: