The entire method is shown in the figure below:

Explained Solution
JAVASCRIPT
OUTPUT
Results will appear here.