JavaScript From The Start: Basic Syntax
Overview
Before we go too far into the realm of cutting edge JavaScript technology, it is critical that we are familiar with the proper syntax and concepts of JavaScript. Writing JavaScript is easy, many people do it every day, but writing good JavaScript is surprisingly a lot harder. This is in part do to the rushed creation of JavaScript as a scripting language for the DOM and also due to the variety of implementations of JavaScript interpreters, each with their own 'oddities', by the major browser vendors over the years. In terms of syntax, JavaScript is visually similar to the C/C++ and Java programming languages, but in terms of function it is actually closer related to the Self and Scheme programming languages. Unfortunately, the visual similarity of the language to the wider known languages of C/C++ and Java make JavaScript programming highly suspectible to confusion and error. The goal of this section is to provide an overview of the JavaScript programming language as if it were the first language that you are learning. That said, it is strongly recommended that you carefully read this section, because JavaScript, even in its most trivial format, is vastly different from the aforementioned programming languages.
Basic Syntax - the var keyword and scope
JavaScript shares a similar syntax to that of C/C++ and Java in its most general form. Variable assignments are done using the equals sign with the variable name on the lefthand side and the value, either direct or through the evaluation of an expression, on the righthand side. The following will take two numbers add them together and store the resulting value, in this case 5, as a named variable of val.
var val = 2+3;
Even with this most trivial of examples, there are many key facets of the JavaScript programming language that we need to discuss and ensure a proper base of knowledge. Notice how the code sample begins with the var keyword which means variable. This keyword identifies the initialization of a new variable within its current scope. The var keyword is not explicitly required by the language for identifying a variable, but it is strongly recommended as a convention of proper JavaScript. When you use the var keyword, it creates a new variable in the current scope, which means that the variable is only available and accessible to to other operations in the same scope or scopes created within the current scope. Before we get too deep, the term "scope" in this context is just a way of describing the lifetime of a variable. In JavaScript, a variable assigned without the var keyword will use either a pre-defined variable with the same name that is accessible by the current scope OR if no such variable is defined, it will set the variable in the global namespace.
NAKEDNOTE: JavaScript Types
Unlike C/C++ and Java, there is no need to declare a type for the variable. This is due to the fact that JavaScript is a dynamic and weakly typed language, which means that the language supports implicit typing and that the type is associated with the value and not the variable. As such, specific enumeration of the type (e.g. integer, string, object, array, etc.) is not required and determined at runtime. This form of typing is present in various other scripting languages including Ruby, Python, Lua, a nd PHP and has various widely debated benefits and downfalls. It is left to the reader to further investigate those benefits and downfalls, if so desired, but for our purposes just know that JavaScript is a dynamic, weakly typed language.
A variable in the global namespace means that any code segment, anywhere in the execution environment can change the value of the variable without you knowing it. Use of the global namespace, while not at all prohibited should be avoided as much as possible because it introduces a large amount of non-deterministic confusion to your code that would otherwise seem to be impossible, especially since it looks similar to other languages. The relationship of variables to their scope is one of the most mystifying and complex elements of JavaScript so it is highly important to get it right at this early stage. Look at this example for a "bad scope" that is not only allowable but an unfortunately all too often occurrence in JavaScript code:
In this code we introduce the print() function which takes any value and attempts to output to the console. If you are testing this in a browser, be sure to use console.log() for the same effect, print() in the browser will print to a printer. The first line attempts to print the global variable empty, which at the time is undefined, hence the error message. The next line looks foreboding, but all it is really doing is creating a function that sets a variable empty to the value of 4 and executes it immediately. The final line runs the exact same code as the first line, but the value has been updated to 4 so it now prints the value of 4. If you are coming from nearly any other language your expectation is that the curly brackets begin and end the lifetime of any variables defined within it, which is known as Block Scoping. Unfortunately, pure JavaScript does not provide for block scoping, hence the reason why the variable empty is set even though it is inside a function. This is because without the var keyword, it will assign it in the highest scope that it either finds an existing variable with the provided name OR the aforementioned global namespace. To see the difference, adding the var keyword to the previous example yields the following expected output:
NAKEDNOTE: JavaScript 1.7 and the let keyword
The JavaScript 1.7 specification, as implemented in the current versions of SpiderMonkey and TraceMonkey, provides a new keyword of let() that provides for more familiar block scoping of a variable. We will investigate the newest version of JavaScript later in this series, but if you want to learn more about the let keyword be sure to review the Mozilla Developer Center regarding what is New in JavaScript 1.7.