Vainolo's Blog

Archive for the ‘tutorial’ tag

JavaScript Tutorial – Part 2: Variables, Functions, and Objects

leave a comment

Previous Tutorial: JavaScript Tutorial – Part 1: Hello JavaScript!

Variables

Javascript is a dynamically typed language, so variables don’t have types (opposite to strongly typed languages such as Ada, Java, or Scala). In general, you can declare a variable anywhere in the program by assigning it a value, but its a very good practice (and helps reduce bugs) to declare variables using the var keyword. You can declare many variables in the same line using a comma (“,”) that separates between them. You can also first declare a variable and then use it in a different place. When a variable is declared but not initialized it receives the value “undefined”.

var foo = 5;
var bar = "hello";
var foobar1 = 'hello', foobar2 = 'world', foobar3; // foobar3 is undefined

As you can see above, comments are added with “//” which comments until the end of the line. You can also add multi-line comments using “/*” to start the comment and “*/” to end the comment.

Functions

Without any types to declare, functions declarations in JS are very compact, including only the name of the function and of the parameters (which are actually optional):

function add(a,b) {
    return a+b;
}

function sayAlert(text) {
    alert(text);
}

The language is very lenient and has no compiler to check that you don’t do stupid stuff (and we all do stupid stuff now and then), so you can call a function that requires one argument with no argument or with two arguments, and this will fail at runtime (maybe):

function addOne(a) {
    return a+1;
}

var b = addOne(1,5); // will return 2, and silently ignore the value 5 passed as parameter
Var c = addOne(); // will return NaN (not a number) because "undefined"+1 is not a number

Functions in JS are treated just like values, so they can be assigned to a variable and executed using the variable’s name:

var add = function (a, b) {
    return a + b;
};

var x = add(1, 2); // x = 3
var anotherAdd = add; // same function, with a different name
var y = anotherAdd(5, 6); // y =11

Treating functions as first class entities gives a lot of power and also reduces lots of boilerplate code that needs to be added in OO languages where everything is an object (like “Comparator” objects in Java).

Objects

Objects in JavaScript are entities that map property names to values, like structs in C. And since we can use functions as values, this allows for the unification of both data and behavior in one place. Objects can be defined inline when declaring a variable, or by defining a function that initializes the properties of the object, a.k.a constructors:

var obj1 = { real: 5, imag: 5 }; // inline object definition

function Complex(real, imag) { // constructor object definition
    this.real = real;
    this.imag = imag;

    this.add = function (otherComplex) {
        this.real = this.real + otherComplex.real;
        this.imag = this.imag + otherComplex.imag;
    };

    this.sub = function (otherComplex) {
        this.real = this.real - otherComplex.real;
        this.imag = this.imag - otherComplex.imag;
    };
};

var c = new Complex(1, 2); // use the "new" operator to create the object
c.add(new Complex(1, 2));
console.info("Real " + c.real + ", imag " + c.imag); // writes "Real 2, imag 4" to the console

c.add(obj1);
console.info("Real " + c.real + ", image " + c.imag); // writes "Real 7, imag 9" to the console

In the example above we first create obj1 in-place, with two properties. After this we define the function Complex which is an object constructor that receives two arguments and initializes the value of the object. Note that the name of the function is in uppercase (convention for object constructors). We also define two object methods that modify the values of the object. To create an instance of Complex we use the new keyword. One interesting thing to note here is that while obj1 is not actually an instance of Complex it can be passed to a function that expects a Complex and things will work just fine, because obj1 contains all of the information required by the function. This gives great power, but with great power comes great responsibility, because (and I’ll say it one more time), there is no typing system or complier checking that you don’t do stupid stuff.

Functions (take two)

Now that we know about objects, we can go back and see that functions are simply objects that are interpreted in a special way. When we define a function, we are actually creating an instance of the Function object behind the scenes, and the interpreter knows how to handle the function calls. So the following three statements create the same function (there may be some differences internally, but superficially they are the same):

function mult(a, b) {
    return a * b;
};

var mult = function (a, b) {
    return a * b;
};

var mult = new Function("a", "b", "return a*b;");

Summary

We covered a lot of material in the tutorial, and this was really fun! I learned lots of new things, and this is just the beginning of a long journey.

Stay tuned :-)

Written by vainolo

April 11th, 2015 at 11:28 pm