systemdebt
systemdebt

Reputation: 4941

Why do I need to use this in ES6 map function

From what I knew, ES6 map automatically binds to this.

                            {
                             cart.products ?
                                <span>
                                cart.products.map( product => {

                                  this.product  ?   //here
                                    <span>
                              blablabla
                                </span>
                                  :
                                  false
                                })

but somehow product is undefined here in the function unless I make it this.product, why is that?

Upvotes: 0

Views: 96

Answers (1)

bharadhwaj
bharadhwaj

Reputation: 2139

I don't clearly understood your query, yet I suppose the problem may be because of the { } you have added on map() function. If you use block within map() make sure you return something from that block.

When writing map() function if there is only a single statement you can avoid using curly brackets as it automatically returns the statement.

array.map(item => item+1)

If you are using curly brackets make sure you use return key word to return back the elements inside the block.

array.map(item => { return item+1 })

Coming back to your example, I think this should work fine,

{ 
    cart.products 
    ?  <span>
            cart.products.map(product => <span> { product } </span> )
       </span>
    :  false 
}

or

{ 
    cart.products 
    ?  <span>
            cart.products.map(product => { return <span> { product } </span> })
       </span>
    :  false 
}

I don't see any use of the condition check inside map() function as it is redundant.

Hope this helps! If not, ping me here with your query.

Upvotes: 1

Related Questions