JavaScript primer

JavaScript Primer

While we don’t have enough space here to cover JavaScript completely, here is a quick overview for those familiar with other programming languages to get started writing your own nodes. To experiment with JavaScript, you can use the JavaScript console supplied with your favourite browser or startup node.js to run the Read-Eval-Print-Loop (REPL) on your machine.

Variables and Variable Assignment

Variables are declared as follows:

  1. var myFirstVar;

Declarations can be separated by commas on the same line:

  1. var myFirstVar, mySecondVar;

They can be assigned with some initial values using the equals operators.

  1. var myFirstVar = 0;

Types

JavaScript supports various types as follows:

Listing 5.1 The basic types supported by JavaScript

  1. var anInt = 0;
  2. var aFloat = 2.5;
  3. var aBoolean = true;
  4. var aString = “This is a string”;
  5. var anArray = [1,2,3];
  6. var anObjectLiteral = {
  7.     someField : “Some value”
  8. };
  9. var aFunction=function() { return; }; // function
  10. var re = /ab+c/;        // regular expression

You can instantiate an object using the new operator like this:

  1. var aDate = new Date();

Comments

Comments can use the double slash single line or the C-style multiline comment format:

Listing 5.2 Comments in JavaScript

  1. // this is a single line comment
  2. /*
  3.    This is a multi-line comment
  4. */

Basic Operators

The built-in numerical operators include the usual: + (addition), – (subtraction), / (division), * (multiplication) and % (modulo).

Listing 5.3 numerical operations in JavaScript

  1. var a = 6;
  2. a = a + 1; // a is 7
  3. b = b % 2; // b is 3
  4. a++; // a is 8
  5. a–; //a is 7
  6. a += 3; // a is 10

Strings can be concatenated as shown:

Listing 5.4 String concatenation in JavaScript

  1. var aString = “The value of a is ” + a;
  2. var greeting = “What a very “;
  3. greeting += “nice day”;

The typeof operator returns the type of a variable.

  1. typeof aString; // returns “string”

To determine the class of an object, for example to distinguish between arrays and other objects, the Object.toString method can be used as follows:

Listing 5.5 Determining a JavaScript object type

  1. Object.prototype.toString.call(new Date()); // “[object Date]”
  2. Object.prototype.toString.call([1,2,3]); // “[object Array]”
  3. Object.prototype.toString.call({someField:12}); //”[object Object]”
  4. Object.prototype.toString.call(function(){return;}); //”[object Function]”

Conditionals

You can use the comparison operators, < (less than) > (greater than) <= (less than or equal) >= (greater than or equal) == (equals) != (not equals) in if statements as follows:

  1. Listing 5.6 Conditional operators in JavaScript
  1. var a = 1;
  2. var b = null;
  3. if (a > 0) {
  4.   b = “a is greater than zero”;
  5. } else {
  6.   b = “a is zero or less”;
  7. }

To shorten this, one could use the conditional operator as follows:

  1. var b = (a > 0) ? “a is greater than zero” : “a is zero or less”;

Loops

Javascript supports for and while loops:

Listing 5.7 For and while loops in JavaScript

  1. for (var i = 0; i < anArray.length; i++) {
  2.     console.log(myArray[i]);
  3. }
  4. while (x < 10) {
  5.     console.log(x++);
  6. }

Functions

Functions are created like this:

Listing 5.8 Declaring a function in JavaScript

  1. function addOne (x) {
  2.     return x + 1;
  3. }

To call a function, you can call them as follows:

  1. var y = addOne(5);        // y = 6

Or, if the function is a method of an object, for example a Date object:

Listing 5.9 Calling a function in JavaScript

  1. var d = new Date();
  2. var year = d.getMonth();   // returns 0 for January, 1 for February,

Callbacks

Node.js is an event-based framework with only one thread of execution. To allow more than one task to execute while performing I/O or waiting for a timer to expire, callbacks are used extensively. For example, to log ‘done’ to the console after 2 seconds, you can use an anonymous function callback as follows:

  1. setTimeout(function() { console.log(‘done’); }, 2000);

You can use functions to process an array:

Listing 5.10 Arrays in JavaScript

  1. var friends = [“mike”,”roberto”, “rodger”, “ted”, “daniel”];
  2. friends.forEach(function (eachName, index){
  3.   console.log(index + 1 + “. ” + eachName); // 1. mike  2. roberto  3. rodger  4. ted  5. daniel
  4. });

Exception Handling

Exception handling can be used to catch errors in your code. To do so, wrap your code in a try/catch block as shown in Listing 5.11.

Listing 5.11 Handling exceptions in JavaScript

  1. try {
  2.     // try to do something
  3. } catch (e) {
  4.     // handle errors
  5. } finally {
  6.     // this block is always executed regardless of whether there was an exception
  7. }

That’s the end of this JavaScript overview. Those new to JavaScript should now have enough knowledge to get going. Let’s start out by writing some basic function nodes! Don’t forget, if you feel you don’t understand the JavaScript, it’s worthwhile taking a look at one of the many JavaScript primers available on the web.