Look At This Bug I Found (ep 01)
So i was working on VSC earlier today, coding a passenger-counter-app i had learnt to make on Scrimba. After completing the code, i decided to run it on the live-server.
Then i saw this ->
Fig1
That 1 wasn't supposed to be there!
It was supposed to look like this
Fig 2
So i went back to my code and wondered what i was doing wrong. Here is my initial code >>
Fig 3
Yeah. Yeah. Silly me!
I intuitively figured that the problem was with the function so i deleted the save() at the end of its function
This is what happened. A bit of a solution but also a new problem.
Fig 4
The 1 has disappeared from before "Previous entries:" and was now appearing below 'People entered'. It shouldn't be here either because it sets the initial passenger count to 1, which is wrong. We want the passenger counter to start counting from zero to perfectly capture the exact number of people entering the train station.
One solution. More problem. So i deleted the increment() too
And voila the problem was gone! Hurray!
Fig 5
Hmm but what happened here
Fig 6
It was obvious to me that the issue here was calling the javascript function but i was a little surprised too because i expected you had to call a function for it to run. As confused as i was, i decided to text my man Alfred, the one you all know as 'Google'.
Fig 7
The gist of both links is that when you call a function at the end as i did earlier, you grant javascript the permission to execute that function immediately but since we only we want this function to be executed only when we click on a button here, we need to remove this permission and write the code like this:
Fig 8
What happened in Fig1 was that the increment() executed immediately, returning count = 1, the save() took this value and saved it which is why you have one there as you see in (Fig1)
On the other hand, when i deleted the save() and kept the increment(), i allowed the increment() to execute immediately which returned 1 under People entered when the page was loaded(Fig4)
Another thing that could have happened is this:
This occurred because i deleted increment() and kept save() thus returning 0- when the page was loaded, what happened here is since the increment() wasn't executed which would have returned 1 as an initial value for the function save(), save() is only able to save 0 which is what is returned when the window is loaded.
TL:DR
Javascript functions are executed immediately when you call them at the end.
Thus, if your code requires the javascript function to only work when you click a button on a page for example then don't call or invoke them.