views:

110

answers:

2

Do the code (e.g. functions) execute at the same time? or it follows the order in which it was written? (top to bottom)? I know that order doesn't matter in CSS and it matters in HTML, what about JavaScript? For instance, if a function it's executed then the next one (bottom one) will execute, or if 2 functions doesn't have anything to do with each other, do they execute at the same time?

A: 

It occurs in the order it was written (with various exceptions). More specifically it's an imperative structured object-oriented prototype based scripting language :)

See Imperative Programming

Rushyo
+2  A: 

It may seem as if Javascript functions are executing in an unpredictable order because the model for Javascript in a browser is event-driven. This means that a Javascript program typically attaches event handlers to DOM elements and these are triggered by user actions such as clicking or moving the pointer over an element. However, the script that sets up the event handlers runs as a traditional structured imperative program.

A further complication is that modern Javascript applications make extensive use of asynchronous functions. This means that a function call might return quickly but will have set in motion an action which completes at a later time. An obvious example is the sending of requests to a server in so-called AJAX applications. Typically the request function is passed a callback function which is called when the request completes. However the Javascript program will go on to the next statement without waiting for the completion of the request. This can be somewhat confusing if you aren't thinking clearly enough about what your program is actually doing.

Another example that you might sometimes encounter is the launching of animations in jQuery. These too work asynchronously and you can pass a callback function that runs after the animation completes. Once again this can be surprising sometimes if you expect the next statement to be executed after the animation completes rather than after it starts.

Rich
Good explanation...So...it doesn't follow an order
janoChen