-1

I am trying to desing the color of a button depending on one input value.

Herefore i am making if clauses to change the const mycolor depending of the input value state1

if(state1=== "good") {const mycolor="green"}
if(state1 === "medium") { const mycolor="yellow"}
if(state1 === "functional") {const mycolor="red"}

console.log(mycolor)

mycolor is not defined, because it is in the scope of the if statement. How can i get access to it?

nt369
  • 57
  • 1
  • 10

2 Answers2

2

Define mycolor outside of the scope.

let mycolor = ''

if (state1 === 'good') 
  mycolor = 'green'
if (state1 === 'medium')
  mycolor = 'yellow'
if (state1 === 'functional')
  mycolor = 'red'

console.log(mycolor)
thchp
  • 2,013
  • 1
  • 18
  • 33
0

Declare the variable outside of the if statement (using let) and then just mutate it depending on the state.

seddouguim
  • 504
  • 3
  • 12
  • You can also use the ternary operator to declare your color variable depending on the state1 variable. const mycolor = state1 === "good" ? "green" : state1 === "medium" ? "yellow" : "red" – seddouguim Oct 13 '21 at 15:54