@Hassan_Garshasb this is a really interesting question. I think the best approach differs, for different people, but there is still general advice I can give.
When I’m trying to solve a problem in code, if it is something simple and small I just do it. If it is something larger, with multiple parts, I tend to get out a pencil and paper, and draw myself a box diagram/flowchart showing the different bits of functionality that need to work together, and draw arrows to show which box’s outputs become inputs for other boxes. Sort of like this, but for individual functions in a program.
Then I look at implementing each part of the code in turn. If I can’t think of how to do it, I immediately start searching the web for useful pages on MDN, stack overflow, etc., for hints or solutions. There is not point torturing yourself for an hour before trying to find out the answer - just go for it. Being able to effectively search for the information you need is a vital skill for good programmers - no one is expected to just remeber it all!
Of course, in your case, this would mean searching around the web for hints and tips, not just going straight to the solution.
If you still can’t get it after doing that, then maybe then is a good time to look at the solution.