Home > Software design >  Can I write arrow function with if on a single line
Can I write arrow function with if on a single line

Time:11-19

For example, I have an array:

arr= ['notebook', 2, 'pens', 'bags', newElement]

I want to find and return the index of 'pens' in the array, how can I write something like:

let found = arr.find(item => arr.indexOf(item) if item =='pens')

CodePudding user response:

If you really want to use an arrow function, you can do this.

arr.findIndex(item => item === "pens");

However, this is unnecessary. You can simply use indexOf:

arr.indexOf("pens");

CodePudding user response:

For return in one line with a condition use shortcut for the if statement. ( condition ? 'if true' : 'if false')

let arrow = () => true ? 'true' : 'false'
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

But you can't write that in find, since find checks the returned value of callback as true or false, whatever you write. What is returned from the callback is processed internally and returns the item inside find not the callback function. IndexOf basically does what you want. Look at this:

function find(array, callback){
    for (const item of array){
        if (callback(item)){// callback function return
                return item                                                  
        } 
    }
}

let array = ['notebook', 'pen']
let res = find(array, item =>item == 'pen')
//let res = find(array, item => (true))// this returns notebook
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related