I’m building a split expense app and right now it is at the basic level where I’m just trying to get the MVP running before scaling it. So I have made 2 functions handleOutstanding and sortByOutstanding. These 2 functions are manipulating demoState[0].travellers array.
I call handleOutstanding function followed by sortByOutstanding but for some weird reason, the array is sorted right before i could even call sortByOutstanding function. Can’t figure out why.
Please check the javaScript code from line 51-93 where all the action is. Ignore the code above line 53. Here is the codesandbox link for the same: https://codesandbox.io/s/go-dutch-app-p3jit.
Aw yes, I spend days trying to figure out this once, I knew the day would come when I would get to save someone a headache…
console.log is asynchronous. Remember that an array is a reference type - it is the address pointing to that place in memory. So, when you run:
console.log(demoState[0].travellers);
You are sending the address, not the data. You are telling the console to print out whatever is at that address. However, before it gets a chance, you sort it. So, even though you called the console.log before the sort, it isn’t being printed until after your sort is done. So, your code is working the way you expect, it’s console that has the odd behavior.
In order to make it behave synchonously, one way is to send a primitive. For example, if I convert it to a string:
As opposed to console.log? I don’t know - I just use console.log and keep that in the back of the head. It doesn’t come up that often. Actually, there have been more than a few experienced devs that were surprised when I explained this to them.