Sneaky False Value In JavaScript

Speaking to Gokhan at work today he pointed out a lovely thing he had just read about JavaScript and false values.

asserts.equals(true, false == '\n');

So even though a blank string is coerced to false, and the abive example is not a blank string. Apparently JavaScript engines escaped characters.

Coders beware JavaScript is here to test you!

JavaScript False Values

In JavaScript you have truthy values and falsey values, and you have to be one of them. If you are the number 1 you are a truth value. If you are the number 0 you are a false value.

There are 6 false values in JavaScript and if your are not a false value, you are a true value.

The 6 false values

null

undefined

0

""

NaN

false

Anything that is one of these values. Or when coerced by JavaScript using valueOf() or toString() will be false! Anything else is true.

var str = "";
var num = 0;

str == num // true

If we do an override on a valueOf we can get an object to return false.

var str = 0;
var obj =
{
    valueOf: function()
    {
        return 0;
    }
};

str == obj // true

You can see that this can be a complicated subject. One that I don’t understand thoroughly enough to continue rambling on. But this post will give you an overview.

&& ||, Using Them To Set Variables

On a course I went on recently I discovered the power behind using operators when setting variables that can really get around all those ifs and block statements.

function updateOptions(myObject)
{
    var options = {};

    if (myObject)
    {
        if (myObject.options)
        {
            options = myObject.options;
        }
    }
}

Would be one way I would apply some defensive programming to get to a variable inside an object.

Another way you could do this much easier is a ternary operator.

function updateOptions(myObject)
{
    var options = myObject ? myObject.options : {};
}

I do like the above example, however there is another way you can achieve this.

function updateOptions(myObject)
{
    var options = myObject && myObject.options || {};
}

So what happens here? The JavaScript engine evaluates from left to right an returns the last truthy value.
Read more about truthy values here

So if myOptions is coerced to true the statement will continue. If myOptions.options is false it will then check the ‘or’ side of the statement, which returns an object.

Namespaces and JavaScript

A big problem in JavaScript is the global scope. Everybody has access to it and other libraries can easily overwrite or use things that you intended to be for yourself.

You can try to solve this with a namespace to encapsulate your code. Then if all your code is in your namespace you will not have to worry about conflicting with other developers JavaScript.

For your namespaces I suggest the reverse DNS style, which if you do not know you can read about it here: What To Call Your Namespaces & Packages.

But JavaScript does not have namespaces
Although JavaScript does not have a namespace or a package keyword, all you need for a namespace is an object.

var com = {};

Because objects in JavaScript are dynamic you can add all of your own objects and modules to this. object.

var com = {};
com.betweenTheBraces = {};

If from this point you load another script and for some reason unknown to us a developer write a function called betweenTheBraces on the global namespace. We have no need to worry as you can only get to our betweenTheBraces through com.betweenTheBraces.

Now of course this code is not good enough. Why? Because if some other library you are loading is using com, you have just overridden it.

Not overriding namespaces
The simple check below makes sure when you are creating your com namespace, a new object will only be created if the first com was evaluated as a falsy value.

var com = com || {};

You can do the same to add your betweenTheBraces package.

com.betweenTheBraces = com.betweenTheBraces || {};

If you know the order you are loading your code then this style of defensive programming may not be necessary.

Overall you can turn your old list of global functions.

function validateInput(input)
{
    // do something
}

function validateForm(form)
{
    // do something
}

function onFormSubmit()
{
    // do something
}

To a nice new namespace something like.

(function(globalScope)
{
    var com = globalScope.com || {};
    com.betweenTheBraces = com.betweenTheBraces || {};

    com.betweenTheBraces.pageValidator =
    {
        validateInput: function(input)
        {
            // do something
        },

        validateForm: function(form)
        {
            // do something
        },

        onFormSubmit: function()
        {
            // do something
        }
    };
}(window));

Here I have created a new namespace for the page validation and wrapped the whole think in a closure. But that is a subject for another day.

From here you may want to read. Creating Classes in JavaScript

What To Call Your Namespaces & Packages

You can practically call your namespace anything you want. Different languages seem to have their own conventions, but the reverse DNS style is what I like the most.

The idea of a namespace is to encapsulate your code, hide it behind folders unique to you. Some of the big libraries will ignore the reverse DNS rule. In JavaScript you’ll find their seems to be no rule at all.

Reverse DNS
Your DNS is unique to you, so it is a great idea to create your namespace using it.

If my domain is www.betweenthebraces.com you drop the www and flip the domain name to create your namespace.

My namespace is com.betweenthebraces.

From this point you can add your project name and any other packages you need.

For example: com.betweenthebraces.myapp.Viewport might be the location of my main class for a mobile application.

The Comma Operator

So I discovered today at a JavaScript training session with Christian Johansen that JavaScript has such a thing as a comma operator!

You may be used to a comma separator, however this is different.

Comma separator

The separator is used in declaring variables, Arrays, Objects and so forth.

var a, b, c;

var arr = [1, 2, 3];

You’ll be used to this by now, but you may not be using it to declare vars. I avoid it on Public API’s as I like to document them individually.

Comma operator

The operator is pretty unique. I have never used it yet, but now I know about it, I may find it creeping into my code.

The rules of a comma operator are that it executes from left to right and only the last value is returned. This means you can execute whatever you want after each comma and you only have to worry about the last value being returned.

var a, b;
var c = (a = 1, b = a + 2, a + b);

alert(a); // 1
alert(b); // 3
alert(c); // 4

Well the code above is pretty useless, however you may start to see the power. This same principle can be used to create a for loop with no body.

var numbers = [];

for (var i = 0; numbers.push(i), i < 10; i++);

alert(numbers); // 0,1,2,3,4,5,6,7,8,9,10

Handy little piece of JavaScript knowledge. If I were you I’d have a little play in your FireBug console.

Creating Classes in JavaScript

There is always a big argument between developers everywhere; Is JavaScript an object orientated language? Well I believe it is!

The key areas of OO are inheritance, polymorphism, abstraction and encapsulation. Now JavaScript may struggle to do all these as perfectly as some of the other languages, but it can do them.

What I’ve noticed is the server side team at work write lots of JavaScript to display their applications. What seems to missing are classes and they stream a shed load of global functions down a page of script. This style of JavaScript can lead to dirty code, that is hard to maintain, messy and tough to reuse.

If you need a reference to the terminology used in this article and what certain words mean, check out this article from Mozilla that briefly explains the terminology of OOP.
https://developer.mozilla.org/en/Introduction_to_Object-Oriented_JavaScript#Terminology

The basics of creating a class

There is no class keyword in the JavaScript syntax, but all Function objects have the ability to become a class when you call it with the new keyword.

function Shape()
{

}

var square = new Shape();

Apart from the fact that this code is pretty useless, by calling the Shape function with new before it, the function returns a new instance of Shape. The instance of Shape now contains prototype and constructor property which is inheriting from Object.

All functions in JavaScript return a value, even if you do not define one. A function without the return statement will return itself.

It is standard practice that all functions that you intend to be used as a class start with a capital letter. The captial tells other developers that you intended the function to be used as a class.

Class constructors

The function becomes the classes constructor function. All the code that you need to execute when new Shape() goes between the braces just like if it was a regular function.

function Shape(width, height)
{
    this.width = width;
    this.height = height;
}

var square = new Shape();

In this example we have added two parameters to the class signature, which assigns the local variables to two public field variables. It is executed as follows.

var square = new Shape(100, 100);

alert(square.width); // 100

Adding functions to your class

There are many ways to add functions to your class and for each way of doing things there are pros and cons. For this blog I am going to stick to the most basic, so not to confuse people just starting out.

In JavaScript there are two types of function. Function definitions function myMethod() {} and function expressions var myMethod = function() {};. Both work equally well and to be honest I am not sure of the actual difference in performance between the two. But if you use a function definition in your class it will be encapsulated and only accessible locally to the function scope. If your function definition is on the top level it will be assigned to the global scope. But scope is a large topic and I will try my best to explain it in a forthcoming article.

Looking at the previous examples if we wish to add a public function called area, it is pretty simple.

function Shape(width, height)
{
    this.width = width;
    this.height = height;

    this.area = function()
    {
        return this.width * this.height;
    };
}

You could also add public functions to the prototype object of your class.

Shape.prototype.area = function()
{
        return this.width * this.height;
};

This is very good for inheritance, and I will be explaining defining functions in this way in an upcoming article.

So we have added a public method. The code is reusable and we are ready to add many public and private functions.

So not to add confusion I will quickly show how you do a private method.

function Shape(width, height)
{
    this.width = width;
    this.height = height;

    function calculateArea()
    {
        return this.width * this.height;
    }

    this.area = function()
    {
        return calculateArea();
    };
}

In the example above I used a function definition to create a private function. You can also create a private function using an expression var calculateArea = function() {}; but just out of personal taste I like function definitions.

The semi colon ; is very important in JavaScript. It can really can come down to whether it will work or not when minified. A tip to remember; a function definition does not need a ; after the block. Where as a function expression is treated as a variable and requires a ; at the end if the line.

There are many other ways that you can add functions, variables, properties and create classes. Here I have only described the simplest way to create a class. In an upcoming post I will be exploring classical style inheritance, scope, getters and setters which will open the doors to a whole new way to structure your script.