Built-in Objects

by phate101101

JavaScript

/**
 * String
 */
function runStrings() {

    var stringLiteral = "My String";
    var stringObject = new String("My String"); // slow

    // String Properties
    console.log(stringLiteral.length);

    // String Methods
    console.log(stringLiteral.toLowerCase());
    console.log(stringLiteral.charAt(1));
    console.log(stringLiteral.concat(" and", " another"));
    console.log(stringLiteral.indexOf("String"));
    console.log(stringLiteral.slice(3, 6));
    console.log(stringLiteral.substr(3, 6));

    console.log(stringLiteral.replace("Str", function (string) {
        return "junk";
    }));

}

runStrings();

/**
 * Number
 */
function runNumbers() {

    var numberLiteral = 5;
    var floatingPoint = 3.14159265359;
    var numberObject = new Number(5);

    console.log(typeof numberLiteral.toString());
    console.log("To fixed", floatingPoint.toFixed());
    console.log("To fixed, 2", floatingPoint.toFixed(2));
    console.log(floatingPoint.toExponential());

}

runNumbers();

/**
 * Math
 */
function runMath() {

    // not a constructor function, its a singleton

    console.log(Math.PI);
    console.log(Math.ceil(Math.PI, 2));

    // to handle decimals and rounding to a decimal...

    // round to 2 places
    var result = Math.round(Math.PI * 100) / 100;
    console.log(result);

}

runMath();

/**
 * Date
 */
function runDate() {

    console.log(Date.now());

    // dates must be constructed

    var date = new Date();
    console.log("Empty constructor", date);

    // value as number of ms since unix epoch, 1970
    var date = new Date(1325376000000);
    console.log("ms", date);

    // date strings
    var date = new Date("January 1, 2012 03:24:00");
    console.log("Date string", date);


    var date = new Date("2012-01-01T08:24:00");
    console.log("Date string", date);

    // note: month starts at 0=jan
    var date = new Date(2012, 00, 01, 3, 24, 0, 0);
    console.log("Date arguments", date);

    // lots of getters and setters...
 ...