skip to Main Content

I want to write a ternary operator in js that do the following:

If index equals 1 or 3, set var x to 10, else set var x to 0.

How do i continue here?

Currently i have this:

let x = 0
const arr = ['string', 'string', 'string', 'string', 'string', 'string etc']

arr.forEach((el, index) => {
  index ? == 1 || index ? == 3
})

2

Answers


  1. You can set the value of x within the forEach loop based on the condition .I’ve added a code snippet.

    const arr = ['string', 'string', 'string', 'string', 'string', 'string', 'etc']
    
    arr.forEach((el, index) => {
      const x = (index === 1 || index === 3) ? 10 : 0
      console.log(`index is ${index} and x is ${x}`)
    });
    Login or Signup to reply.
  2. The above answer works, If you want it to try some variations you can do this as well :

    const arr = ['string', 'string', 'string', 'string', 'string', 'string', 'etc']
    
    arr.forEach((el, index) => {
      //Using `includes()`
      const x = [1,3].includes(index) ? 10 : 0 
      // Shorter Syntax
      const x = index === (1||3) ? 10 : 0
      console.log(`index is ${index} and x is ${x}`)
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search