JavaScript is an important language since it is the language implemented by web-browsers (Internet Explorer, Mozilla, Safari, Chrome, Opera etc). JavaScript is based on ECMA standard; ECMA stands for European Computer Manufacturer's Association (http://www.ecma-international.org). JavaScript supports the latest version of this standard: ECMAScript5.
Contrary to its name, JavaScript has very little to do with the Java programming language! Though, both of these languages support object-oriented programming and have similar syntaxes, their similarity, pretty much, ends there. By comparison, JavaScript is not strongly-typed and is a lot more flexible.
Overall, this JavaScript module can be briefly divided into two parts.
The first section presents various low-level elements of JavaScript that empower it to handle its role. These elements are: variables, objects, arrays, strings, loops, conditional expressions, and functions, arrays, and objects. Along with their description, the text also provides several examples that supplement their understanding.
The most popular role of JavaScript is to enable browsers to handle user interaction and to process their input. And this is where the second part of this modules comes into picture. The second part covers browser-related JavaScript concepts like interaction with HTML, DOM, and event handlers. A good understanding of the constructs covered in the first part of this module would enable the reader to easily master concepts covered in the later part.
Running a JavaScript program is fairly easy. We can embed JavaScript code in an HTML page using tags "<script type="text/javascript">" and "</script>". Any code that sits between these two tags executes in the JavaScript context. And, such a JavaScript code can be placed anywhere in an HTML page and can be placed any number of times. With HTML5, the default script type is assumed to be that of JavaScript, and so we can actually get away with just using the tags <script> and </script> and not explicitly specify the script type as "text/javascript"; we provide "text/javascript" for the sake of completeness. However, HTML4 mandates that we specify the script type.
Since JavaScript is run using a web browser's built-in JavaScript interpreter, there is no need to compile these programs!
We begin by providing below a simple "Hello World!" JavaScript example. As described earlier, we can embed JavaScript code in an HTML file (let us name this file, "hello.html"). This programs prints "Hello World!" in two different styles. In the first style, we use JavaScript's document.write() function to print the string "Hello World!" on the browser. In the second style, we use the innerHTML property of the "idDiv" HTML element to add "Hello World!" to it.
<!doctype html> <html> <body> <div id="idDiv"> </div> <script type="text/javascript"> <!-- Needed for old-browsers that do not understand Javascript. // Get a handle of the div element. var elem = document.getElementById("idDiv"); elem.innerHTML += "Hello World! <br>"; document.write("Hello World! <br>"); // --> </script> </body> </html>
We present two different styles to print "Hello World!" for a good reason.
The first style uses the write() method of the document object and this method prints text on the HTML page. This method was a popular method in the past but its use now is discouraged due to the possibility of it erasing all the contents on a page. Therefore, we would not be using document.write() henceforth.
The second method uses getElementById() method of the document object to get a handle of the "div" element of the HTML body. Next, it adds to the innerHTML property of the "div" element. This method is safe and does not erase existing content. In our examples, we will use innerHTML method for printing text on the page.
Note that we will describe the document object, document.write() method, document.getElementById() method, and innerHTML property in a later section. If you feel overwhelmed, please make a note of these methods and once you have read the later sections, these methods would start to make complete sense!
In-between the script tags, the above example has two lines, one starting with "<!--" and the other one having "// -->". This is a workaround to handle (old) browsers that are incompatible with JavaScript. With this workaround, these browsers see JavaScript code lying between "<!--" and "-->" as HTML comments and thus, ignore it. In that case, why do JavaScript-compatible browsers not see this code as comments? Well, JavaScript engine has a hack for this. It is acceptable for JavaScript code to keep the string "<!--" at the start of the script code and JavaScript simply ignores everything in this line. Now, the last line starts with "//" and since "//" indicates JavaScript comments, JavaScript ignores everything on that line as well. This way, JavaScript does not complain about HTML's closing comment tag, "-->"! Thus, this workaround allows JavaScript compatible browsers to run JavaScript code and JavaScript incompatible browsers to ignore it.
In the above example, we end each line with a semicolon; each of these lines are referred to as a statement. In JavaScript, it is not required to end each line with a semicolon, but when we provide a semicolon, JavaScript does interpret that as an end of statement. While it is okay to not provide semicolon, for cases that have a statement spread over multiple lines, a lack of semicolon can sometimes lead to unknown behavior. Without a semicolon, JavaScript can parse a statement spread over multiple lines as long as it considers them to be making a valid expression. It is this behavior that can potentially lead to confusion! For this reason, we always use a semicolon at the end of each line and we also recommend the same!
Running the above example is very simple. Simply point the web browser to this location to load this file. Once loaded, the page would display "Hello World!" twice.
It is also possible to include a file containing the javascript code directly using the "src" attribute of script tag. For example, let us create a file (let us say hello.js) that holds the document.write command: "document.write("Hello World! <br>");"; typically, JavaScript files have an extension of "js". Now, we can include this file directly as part of the script tag as: <script type="text/javascript" src="./hello.js">. We are assuming that the "hello.js" file is in the same directory as that of the html file. Thus, the following example would also have the same "Hello World!" output.
<!doctype html> <html> <body> <div id="idDiv"> </div> <script type="text/javascript" src="./hello.js"> </script> </body> </html>
Including a javascript file directly in the HTML file has several advantages.
The first advantage with this approach is that we can use the same file in multiple HTML pages instead of having to provide the same code in multiple pages; thus, this provides a better code-re-usability.
The second advantage with this approach is that we can also provide the URL of a javascript file located on an external server. Thus, if we have to include a remote file ("www.codingbison.com/library/foo.js"), then we can invoke that as: <script type="text/javascript" src="www.codingbison.com/library/foo.js">. Clearly, with this approach, a company can provide a simple way to publish a set of API for other users.
The third advantage with this approach is that it makes the HTML code less cluttered and thus, easier to read.
For the sake of readability, we will modify most of the future examples in this JavaScript module in two ways. First, we might skip the comment lines that allow JavaScript-incompatible browser to ignore JavaScript code. We assume that the reader has taken a note of this behavior and we recommend that we should protect JavaScript code using these comment lines in production code. Second, we will embed the JavaScript code directly within the <html></html> tags instead of keeping them in the <body></body> tags.