In general, compiled languages(Java, C, C++) and run-time languages(PHP, Phyton, JavaScript) have different scoping rules and execution order. I would suggest you to learn execution context for JavaScript to figure out basic understanding of how code is executed. Look at this post, http://www.yusufaytas.com/javascript-execution-context/