Tuesday, November 13, 2012

Javascript Note 1

Things I learned while writing a Thai transcription script in Javascript.

  1. The "keys" of an array are the indices!
    var myarray = [ "potatoes" "tomatoes" "celery" ];
    var sample = [];
    for (var x in myarray) {
        sample.push(x);
    }
    // sample = [ 0 1 2 ]   NOT  [ "potatoes" "tomatoes" "celery" ]
    

  2. Primitives are passed by value and the references of Objects are passed by value.
  3. this in a method refers to the object from which the method was invoked. See JavaScript “this” keyword.
    var m = function() {
        this.value = this.value +1;
    }
    var a = { "value":1, "m":m };
    var b = { "value":100, "a":a };
    
    a.m();          // a.value = 2
    b.a.m();        // a.value = 3, b.value = 100
    b.a.m.call(b);  // b.value = 101 
    

  4. Objects in Javascript are associative arrays. To create an object is to create an associative array. One way of doing this is through the use of functions.
    function f() {
       var x = 1;
       
       this.y = 100;
       
       this.addup = function addup(v) {
          this.y = this.y + v;
       };
       
       return this;
    }
    
    var func1 = f();
    var func2 = f();
    
    func1.addup(1);
    [ func1.y, func2.y ];  // [ 101, 101 ]
    
    func2 = new f();
    func2.addup(5);
    [ func1.y, func2.y ];  // [ 101, 105 ]
    
    [ func1.x, func2.y ];  // [ NaN, undefined ]
    

    The last line is strange (Mozilla). I personally think it's a bug. I was expecting undefined. See Which way is best for creating an object in javascript? is “var” necessary before variable of object?.
  5. undefined is not a keyword in Javascript. It is just another variable that generally is undefined. The safest way to test if variable x is undefined is typeof(x) == "undefined". Note
    var a = "welcome";
    var b = { "a":"apple", "k":"kite", "z":"zebra" };
    
    b["b"] == null;       // TRUE
    b["b"] == undefined;  // TRUE
    b["b"] === null;      // FALSE
    b["b"] === undefined; // TRUE
    

    However starting in Javascript 1.8.5, undefined is a global non-writable variable whose type is undefined. So
    var undefined = "trickster";      // doesn't do anything
    
    undefined === undefined;          // TRUE
    typeof(undefined) == "undefined"; // TRUE
    


2 comments:

  1. C has = (assignment operator), == (equivalence operator) but no ===!

    ReplyDelete
  2. Yes, that's right. === means "same object as". In C, you can test for "same object as" (using the word "object" loosely here) by comparing memory address. If two objects have the same memory address, then they are the same. But because there is no reliable way to get the memory address of objects in Javascript, they had to create the === operator. On a related note, in Java, Object.equals() is used for equivalence and == is used for "same object as".

    ReplyDelete