Before learning JavaScript, it's important to learn how it fits into the larger picture of the Browser and DOM (and your webapp).
To start, lets walk through a very basic "Hello World" webpage. Assume that the server at helloworld.com has this HTML file. What happens immediately after a user enters the URL for helloworld.com and presses enter
?
-
First, the browser creates a HTTP request for index.html. The server returns the HTML as part of the HTTP response.
-
The browser feeds the HTML to it's DOM engine which begins processing the HTML and building a HTML document and it's HTML elements. For example it will create a
DocumentElement
when it sees anhtml
element, and add a childhead element
when it sees that. When a script tag is encountered, the browser passes the contents of that script tag to it's JavaScript engine to be evaluated. -
The JavaScript engine tokenizes and parses the code and then runs it statement by statement. When it sees
alert("Hello World")
, it looks up alert, and then calls it with "hello world" as an argument. Alert pauses JavaScript. Once the user clicks ok, JavaScript moves to evaluate the next statement ... which in this case, there is none. -
When JS has finished running, the DOM resumes processing the remaining HTML. It creates the
body
element and theH1
element, displaying the Hello World to the user.
Code in languages like Java or C is compiled to byte or machine code. When your app runs, it reads instructions from code and operates on data.
Dynamic Languages, like JavaScript are different. Instead of a strong separation between code and data, your application's code and data is built one statement at a time. You are effectively programming your program.
For example, what happens when a script tag like <script type='text/javascript' src='myapp.js'></script> loads the following code?
var JS = {};
JS.says = function(message){
alert('JavaScript Says "'+message+"'")
};
JS.says("Hello World");
After making an HTTP request for the contents of myapp.js, it passes the contents to the browser's JavaScript engine. The JavaScript engine tokenizes, and parses the code. Then it runs each statement, one at a time, building your program in memory. Lets look at this visually:
Dynamic Language
Explanation of graphical representation of JavaScript Types Primitive v Object Types
Functions
- functions don't belong to any object / class
- "this"
- Closures
Prototypal Inheritance
- DOT operator
- NEW operator