-1

I'm trying to make background-color to swap after X time, and its working BUT after last iteration where step is set to 0, what I'm getting is undefined and I can't figure it out why : /

const foo = () => {
  const colors = [{
      primary: 'LightGreen',
      secondary: '#7fe27f'
    },
    {
      primary: "Gold",
      secondary: '#efc900'
    },
    {
      primary: "#1590FF",
      secondary: '#0479FF'
    },
    {
      primary: "#00BFFF",
      secondary: '#06ace3'
    }
  ]
  let step = -1
  return setInterval(() => {
    step === colors.length ? step = 0 : step++
      return console.log(colors[step]);
  }, 2000)
}

Any ideas why is that happening? And how I could fix it?

Andreas
  • 21,535
  • 7
  • 47
  • 56
  • _"and its working"_ - Really? `foo` will always [return the id of the created timer](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval). The "inner" `return` would return `undefined` because `console.log()` doesn't return anything. But -> [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call); And that's not the way how the [ternary operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) should be used. – Andreas Mar 24 '20 at 17:15
  • It's just quick drawing from my react code, I wanted to omit all useEffect, useState and unnecessary code for simplicity ;) But thanks anyway! – Daniel Wiśniewski Mar 24 '20 at 17:21

1 Answers1

0

When step is equal to colors.length - 1, you will perform step++, which will make step === colors.length. Then you will access colors[colors.length] which is undefined.

You have to check whether step === colors.length - 1 in your condition.

But a better solution would be to use the remainder operator. You can just do:

console.log(colors[step++ % colors.length]);
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143