JavaScript | Types and Comparison

by Zoltan Boros

HTML

<pre id="out"></pre>

JavaScript

var outElement = document.getElementById("out");

function print(text)
{
    if (typeof text !== "undefined") {
        outElement.innerHTML += text;
    }
}

function println(text)
{
    print(text);
    print("\n");
}

function printType(x)
{
    print("Type of " + x + ": " + typeof x);
    if (typeof x === "object") {
        print(" (" + x.constructor.name + ")");
    }
    println();
}

function compare(a, b)
{
    print(a + " (" + typeof a + ")  < " + b + " (" + typeof b + ") :" + (a <  b));
    println();
    print(a + " (" + typeof a + ") == " + b + " (" + typeof b + ") :" + (a == b));
    println();
}

printType(true);
printType(new Boolean(false));

printType(1);
printType(new Number(2));

printType("Foo");
printType(new String("Bar"));
println();

compare(false, true);
compare(new Boolean(false), new Boolean(true));

compare(true, false);
compare(new Boolean(true), new Boolean(false));

compare(true, true);
compare(new Boolean(true), new Boolean(true));

compare(1, 2);
compare(new Number(1), new Number(2));
compare(new Number(2), new Number(1));
compare(new Number(3), new Number(3));

compare("foo", "bar");
compare(new String("foo"), new String("bar"));
compare(new String("bar"), new String("foo"));
compare(new String("foo"), new String("foo"));

var date1a = new Date();
var date1b = new Date(date1a.getTime());
var date2  = new Date(date1a.getTime() + 60000);
compare(date1a, date1b);
compare(date2, date1a);