16.1. JavaScript SyntaxWe call the look of a programming language its syntax. Java is a fairly traditional programming language in terms of its syntax. It doesn't look much different than C or C++ or other languages. Java was designed to make it easy for C or C++ programmers to learn. Languages like Scheme and Smalltalk look much more different. There are several things that you should expect to be different and that you'll need to explore when comparing the syntax (look) of different languages:
JavaScript is meant to be a scripting language. This means that it's meant to be used easily, by non-professional programmers, to solve relatively simple tasks. No one is going to use JavaScript to write the master calculation program for the IRS, nor something that tracks all the accounts for owners of MasterCards. It's designed to look a lot like Java (and C), to make it easier to pick up for people familiar with those kinds of languages. JavaScript can be used to program the Web server or interact with the viewer of the Web page on the client. We're going to emphasize the latter. When JavaScript is used on a client machine, it's actually executed by the browseryour browser contains a JavaScript interpreter. We call this client-side JavaScript. In JavaScript, variables are supposed to be declared before use, but you don't have to specify their type. The type will be determined based on how you use it. However, JavaScript isn't strict about thisyou can simply say a = 12;. But it's more correct to declare the variable as something you'll be using by either typing something like var a = 12; or: var a; ... a = 12; Like Java, JavaScript defines blocks using curly braces. You can use any indentation you want, but the block begins with a curly brace and ends with a close curly brace. function test() { document.writeln("This is a test"); } In Javascript you can define functions which are like Java methods. The above code defines a function named test that doesn't take any parameters and writes to the HTML document the string This is a test. We'll find many similarities and differences between Java and JavaScript when we get down to writing individual lines.
But in a real sense, these are just details. The basic operation of JavaScript is not unlike Java. Statements are still executed one after the other, there are still variables, loops, and conditionals, and we'll still have functions and methods. All of what you knew before still applies. JavaScript is all about objects. Just about every function is actually a method. There isn't a global print, and there's not even a global write or writeln. Instead, to write into the document, we'll use document.write() (or, to end the line with a newline, document.writeln()). The document here is the HTML document itself. |