JavaScript code is executed during page loading or when the browser fires an event. All the statements in JavaScript are executed at page loading, even if most of the statements are just functions that are not used until the user interacts wit the site.
Function calls or code can be attached as "event handlers" via tag attributes that are then executed when the event is fired by the browser. For example, clicking a button could screen could trigger a piece of code in the JavaScript to do something. (i.e. change the color of the button).