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
})
>Solution :
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}`)
});