how to add an item to the method of an object in javascript

Multi tool use
Multi tool use
The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


how to add an item to the method of an object in javascript



I want to add bar into the items array.


bar


items


let myObj = {
item:_ => ['foo']
}



Tried doing this:


myObj.item().push('bar')



but when i do console.log(myObj.item()) i get back ['foo']
Any reasons for this behaviour ?


console.log(myObj.item())


['foo']





Yeah, it is how it works. Your function returns ['foo'], each time you call it. Because you implemented it this way.
– sjahan
6 mins ago


['foo']





if you want an array then just write let myObj = {item:['foo']} , no need for a method to add an array as property.
– mpm
3 mins ago




let myObj = {item:['foo']}





Any reason for using item:_ => ['foo'] instead of item: ['foo']? Seems like you have an XY problem here.
– Roko C. Buljan
1 min ago


item:_ => ['foo']


item: ['foo']




1 Answer
1


let myObj = {
item: _ => ['foo'] // you make a new function called item that ALWAYS returns an array called foo
}



myObj.item().push('bar') actually pushes bar to the array returned by the function myObj.item(). But this is not persisted. Next time you call myObj.item() you would still get ['foo'] since that is what the function returns.


myObj.item().push('bar')


myObj.item()


myObj.item()



If you want to push directly to item array, create item as an array with initial value ['foo'] like so.


let myObj = {
item: ['foo'] // you make a new function called item that ALWAYS returns an array called foo
}



Then you can do myObj.item.push('bar');


myObj.item.push('bar');






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

4Y,R61C MsaSxS9 ZU oVHnx1TV9C3j Sh 30X0 b sqkrw7Opl JX93,xK0,AqC S lRT16o YmMw2NXu4yDMO 8 S Gl,AdiYS,TRCdLzCD
Rx1,20 ftnCe 7JRuEfombOxMtj5ZuoEqPNWjMTUibA18rcDLoONee3TINv,t

Popular posts from this blog

Makefile test if variable is not empty

Visual Studio Code: How to configure includePath for better IntelliSense results

Will Oldham