@jasveer-code,
I have to say this at the start, you need to make your code more readable. This is a BIG reason for why you don’'t understand what is happening.
If you have code that is nested inside a block, indent it, so you can easily understand what is inside the nested block and what isn’t.