Introduction to JavaScript for C++ and Java Programmers

When I first learned how to program, the course that I took used the C++ language to demonstrate core programming concepts.

When I first encountered the JavaScript programming language in the development environment at my company nearly three years ago, the first thing that I noticed about it is that the code looks almost exactly like C++ code. In fact, many of the keywords have the exact same meaning. This is a blessing and a curse for JavaScript. On the one hand, this syntax is very familiar and easy to use for the multitudes of programmers familiar with C++ and Java, but on the other hand, this seeming familiarity masks the great differences between these languages.

The best way to compare Java and JavaScript is to say that Java is to JavaScript as car is to carpet.

Before I go any further, I would like to acknowledge the writings of Douglas Crockford, which I greatly benefited from as I taught myself to use JavaScript.

If you've come to this page, you are almost certainly a web developer. That is because JavaScript is the de facto scripting language of the World Wide Web. There have been several languages proposed as alternatives to JavaScript (the best-known example being VBScript), but none of them ever gained widespread acceptance for this purpose. It is also good to know that the JavaScript alternatives "CoffeeScript" and "Dart" all compile to JavaScript. The upcoming HTML5 standard is anticipated to make JavaScript an even more integral component of the World Wide Web as we know it, so I seriously doubt that JavaScript is going anywhere anytime soon.

This is not even close to being an exhaustive reference. This is a crash course. It is meant to help you get on your feet and avoid common beginners' mistakes.

Green Text Boxes

Each green text box on this page contains a working example of JavaScript code. The JavaScript interpreter in your browser can be instructed to read code from the page and execute it. When you click on a "Run Code" button next to any green text box, the code in the text box is interpreted and executed. I put the code in editable text boxes for a reason. I want you to be able to tinker with the code and try different things. Make something interesting happen!

The principal differences between JavaScript and C++

I would like to begin by explaining the principal differences between JavaScript and C++.

Loosely Typed

I believe that the best way to explain these differences is with some examples. Let me begin with JavaScript's loosely typed nature. In C++, you might write code like this:
int x = 1;
int y = 2;
bool b = (x + y) < 5;

In JavaScript, you would simply write this:
var x = 1;
var y = 2;
var b = (x + y ) < 5;
In JavaScript, variables are always declared with the var keyword and types are inferred at run-time.

In C++ and Java, classes have functions and fields. An object can be instantiated to be an instance of a class so that it has the functions and fields specified by the class definition.

In JavaScript, it is a bit different. There are no classes in JavaScript, there are only objects that have a set of objects (Remember that functions are objects in JavaScript). In JavaScript, there is no class definition, only a constructor function. Allow me to give another example. In C++, you could write:

In JavaScript, the equivalent would be this:

To instantiate a Dog in C++, you would write Dog dog = new Dog(). In JavaScript, it would be almost the same, but you would use the var keyword as previously explained: var Dog = new Dog().

In my experience, one of the drawbacks of JavaScript is that it makes it more difficult sometimes to tell what type of data an object should contain. Suppose I write the following function in C++:

In JavaScript, the equivalent function would be

The C++ speakTwice function has a function signature that says that it is only valid to make this function call with a Dog object as a parameter. This is not the case with the JavaScript function. The function signature says nothing at all about what type of argument p_dog is. The is also a blessing and a curse. I can call speakTwice with any argument, so long as that argument has a function called speak! The following would be valid:

speakTwice( { speak: function() { return 'hello!'; } } );

This is a good time to introduce JavaScript's object literal notation. In the Dog example, I created an object using a constructor function. In the last example, I used an object literal. An object literal consists of a comma-separated list of key:value pairs enclosed in braces. In the last example, I specified an object with a single value "speak", which has, as its value, a function that returns 'hello!'. This is convenient because it allows you to specify any object you want without having to write a class definition for each one. This is called duck typing. Here's another example:

Prototype Inheritance

Prototype inheritance is a feature of the JavaScript programming language that you will almost certainly fail to take advantage of if you simply try to think of it is being like C++ or Java. Prototype inheritance seems confusing at first, but it can be learnt in a rather straight-forward fashion.

Remember that there are no class definitions in JavaScript, only constructor functions. A prototype is an object property that is applied to constructor functions to say that whatever objects produced by that constructor function inherit from the specified prototype. Here is an example. In C++

TODO: Write much more here! also, later on, need to write more about built-in functions and DOM

First Class Functions

First class functions is one of JavaScript's best features.  The concept is very simple: functions are objects just like numbers, strings, arrays, and everything else.  They can be declared, used in-line, assigned to variables, passed as arguments to a function, and returned from functions.  This sounds exotic if you're coming from using C++, Java, or some other language that doesn't have first class functions, but as mentioned above, first class functions are a feature of the Scheme programming language that first appeared in 1975.  Note that when a function is declared in-line without being given a name, it is known as an anonymous function. Here are some examples:

The following is an example of passing a function as an argument to another function. Here, I have one function that iterates over all the numbers from 1 to n and calls a function for each one. A common example of where you might want to do that is to compute the factorial of a number. Here, I have generalized this concept so that you can do any operation that involves calling a function from all the numbers from t to n. Note how the style of the code here is completely different from anything possible in C++. The closest thing in C++ that comes to mind is abstract functions.

I am aware that the following example will seem contrived, and that's because it is. In real-world examples, you may want to return a function to be called in an entirely different part of your JavaScript program. This is particularly useful when you want to give another part of your program access to perform an operation on an object without giving it full access to that object. This works great for encapsulation. In this example, counter acts just like a private field does in C++. What's happening is that the Secret class has a function to display a message and increment counter. However, I don't want to give direct access to the Secret class to the public class, so I write a single function that returns a reference to just the one function in the Secret class.

More About Functions in JavaScript

There are two more particular facts that every serious JavaScript developer needs to know about functions in JavaScript.  In the scope of every JavaScript function, there is an object called "arguments".  arguments is an array-like object that contains all the arguments passed to the function.  However, arguments is not an array and is unaffected by changes to the array prototype.  arguments has a length property equal to the number of arguments passed to the function.  It also has a "callee" property, which holds a reference to the function itself.  This is useful for unambiguously writing recursive functions, and necessary for writing anonymous recursive functions.  The first example following shows a recursive factorial function in JavaScript.

I have not told you this yet, but JavaScript allows a function to be invoked with any number of arguments, regardless of the number specified in the function signature.  If fewer arguments are passed than there are arguments in the function signature, then the missing arguments are defined to be null.  If there are more arguments passed that there are arguments in the function signature, then the arguments object must be used to read those arguments.  Here is an example.

Function Scope

Scope works a bit differently in JavaScript compared to Java or C++.   Variables in JavaScript have function scope.  This may seem like a trivial difference at first, but it is an important part of the language.  With first class functions, functions as constructors, and function closure, Douglas Crockford refers to the function keyword in JavaScript as "function, The Ultimate".  Once you understand these concepts, you will see no need for the keywords that JavaScript doesn't have: class, public, private, abstract.  There is only function, The Ultimate!

Built in functions and objects: all you get!

I would like to survey some of the more commonly used built-in functions in JavaScript. This is, by no means, a complete introduction. When all else fails, read the directions. If you Google for information about common JavaScript objects and functions, you are bound to end up at w3schools. I have found much useful information there, but be aware that w3schools has no recognized authority over the JavaScript specification. w3fools offers some criticism of w3schools, as well as a list of alleged inaccuracies.

What I will do here, is I will provide a link to the Mozilla Developer Network pages about common objects. I will emphasize some of the most commonly used properties and functions of each object, but I will only enumerate a few of them.

The string object (MDN)

Every string that you declare in JavaScript inherits the string prototype.

toUpperCase() and toLowerCase() are two commonly used methods; these should be self-explanatory. For those of you familiar with regular expressions, the string object has a match() method that takes a regular expression and returns a boolean value indicating whether the value matches the regular expression or not.

split() is probably the string method I use more than any other method. I frequently encounter data that is formatted like this: 'Value A, Value B, Value 1, Value2'. I need to refer to the data logically as an array. split() takes, as an argument, a character that logically separates the values and returns an array of the separated values.

The number object (MDN) and the Math (MDN) object

Every number that you declare in JavaScrit inherits the number prototype. One of the single most important things you can know about the number prototype in JavaScript is that every number in JavaScript is a 64-bit floating-point value. In JavaScript, there are no integers, long integers, short integers, or long double-precision floating-point decimal values. There is only one number prototype. Unfortunately, this can lead to the same sort of confusion with round-off error that it does in C/C++.

There are three special number values to be aware of: Nan, Negative_Infinity, and Positive_Infinity. Use the built-in isNan and isFinite functions to test for these.

The Math object contains a number of built-in functions and values for algebra and geometry. Also, it contains a function for generating pseudo-random numbers. The next code sample shows how you can use the Math object to illustrate that the sine and cosine value of a given angle conform to the rule that the square of the sine and cosine of any angle is 1. Note that due to the round-off errors inevitable from forcing transcendental mathematical functions to be estimated by functions that return floating-point values, I will not test that the sum of squares is exactly 1; I will test that it is within a small limit of one.

When the user enters a number or you read one from a file, you may have a string literal on your hands. There are two built-in functions for reading a number from a string: parseInt (MDN) and parseFloat (MDN). They are global functions, not part of the number or Math object. Use parseInt to convert an string to an integer and use parseFloat to convert a string to a floating-point value. parseFloat takes only a single argument: the string that represents the number. However, parseInt is another story. It takes a second argument that specifies the radix of the integer. Ordinarily, the radix of the number is inferred. This isn't such a great feature because almost all of your users will be entering values in base-10. In particular, parseInt("012") will be interpreted as 10 because JavaScript expects a string that starts with 0 to represent an octal value. To avoid this, always specify the radix as 10. Allowing the interpreter to guess the radix from the user's input is a recipe for trouble!

The Array Object (MDN)

As a web developer, I extensively use the Array object to represent records that are retrieved from a database. JavaScript arrays contain 0 or more elements and are zero-indexed. You will find huge differences in performance comparing array manipulation performance on different versions of various web browsers.

One of the biggest pitfalls with JavaScript array is that they are reference objects; when you declare an array and assign it to an object and subsequently assign it to another object, both objects contain a reference to the same array. In order to make a copy of the array, it is necessary to enumerate the array and copy it, value by value. This is even more fun when the elements of the array are complex types, themselves. Use the push() and pop() array mehthods to add and remove elements from the end of an array.

Suppose that you get some data back from SQL and you want to be able to sort it by multiple fields depending on your user's needs? The JavaScript Array prototype provides the sort() method. This method is a great example of how JavaScript works with first-class functions. sort() takes, as an argument, a comparison function that takes two arguments. The built-in sort() method will use the comparison function to determine the ordering of the array. The comparison function should return -1 if its first argument should come before the second argument in the sorted array, 1 if it should come after, and 0 otherwise.

The code below gives an example of sorting an array with records of three people. This code performs two sorts: one by last name, and one random 'sort'. The records are sorted at random by passing Math.random as the comparison function. Remember that even though Math.random expects no arguments, it is legal to invoke any function with any number of arguments in JavaScript. Furthermore, the comparison function doesn't have to return -1, 0, or 1; any floating-point value will do.

Perhaps one of the most useful functions on the Array prototype is join(). join() takes the string representation of each element of the array and concatenates them all together with an optional separator character. Recall the string.split() I introduced earlier that converts a string to an array. join() does the opposite, and it will perform the operation much, much faster that you can do it by simple string concatenation. Learn to recognize string-concatenation within loops as a bad practice to be avoided and you will avoid having frustrated users complaining that your page so d**n slow.

When you run the following example, the code will prompt you for a number of loop iterations. The code will concatenate a single-character string on to itself the specified number of times using both join() and string concatenation.

I encourage you to try running this code in older browsers. Using join() is considered the best practice for concatenating a large number of strings to the extent that some newer browsers will automatically optimize string concatenating code to use it even if it isn't programmed to.