Archive

Posts Tagged ‘type’

Javascript 101 Week 1 Assignment

January 29, 2011 8 comments

As I blogged previously, I am starting to learn Javascript via P2PU.org/Mozilla School of Webcraft. Here are my answers to the first week’s assignment.

Questions

The alliance of Netscape and Sun Microsystems did not use Java in the browser, because it was not suitable for that purpose. Why do you think Java was not suitable to be embedded in a browser?

I don’t think Java is suitable for embedding in a browser for a few reasons. Firstly, while the Just in time compiler does a great job at optimizing code that runs over and over again, there is a big cost to starting up the JVM, as it must load dozens if not hundreds of class files.

Furthermore, developing web applications in Java would be very slow for the developer too, as the code would have to be compiled into bytecodes before it could be run. Webapps written in Java have this problem already; if all the client side scripting were done in Java, this would be unbearable.

Furthermore, Java is not a good scripting language because it is too verbose, and the strict type checking is often overkill for simple scripts.

We are advised to provide a radix, because Javascript stops parsing at the first nondigit number. If the number starts with 0, this makes Javascript believe the number is octal and that any character other than 0-7 is invalid. Thus parseInt(“09”) == 0.

What is a type, and why do you think types are useful in writing programs?

A type indicates the ‘flavor’ of a variable, i.e. what the ‘tentacle’ grasps (using the terminology of the Eloquent Javascript course. Types are very useful for ensuring that the operations we invoke on variables make sense. For instance, it makes sense to invoke the times binary operand on two numerical values, but it doesn’t make sense to invoke it on two Strings, or a String and a number.

Why do we lose precision when performing operations with decimal numbers in Javascript? Can you think of a few implications of why this would be a problem?

All numbers in Javascript are stored as doubles (64 bit floating point numbers), which have a finite precision. Certain numbers cannot be exactly represented in this format, such as 0.1 (it has a nonterminating binary representation, and thus cannot be exactly represented in a finite number of digits). This means we have to be very careful when working with numbers, because our intuitive sense is wrong.

.1 + .1 + .1 + .1 + .1 + .1 + .1 + .1 + .1 + .1 = 0.9999999999999999

Do you understand why the following operation produces the given result 115 * 4 – 4 + 88 / 2 = 500

Yes – order of operations matters. * and / have higher precedence over +. If you want to change this, use parentheses to explicitly show the order you want.

What does typeof 4.5 do, and why does typeof (typeof 4.5) return “string” 

Typeof returns a string representation of the type of the argument. typeof (typeof 4.5) returns string, because typeof returns the string “number”. The piece in parentheses is executed first, with that result becoming the argument to the outer typeof call.

Exercises

2.1

(4 >= 6 || "grass" != "green") &&
   !(12 * 2 == 144 && true)

(false || true) && !(24 == 144 && true)
(false || true) && !(false && true)
(true) && !(false)
(true) && (true)
true

2.2

function while_exponent(val, exp) {
    var product = 1;
    var counter = 0;
    while (counter < exp) {
        prduct *= val;
        counter++;
    }
    return product;
}

2.3

function while_triangle(n_lines) {
    var line_counter = 1;
    while (line_counter <= n_lines) {
        var string = ""
        var inner_counter = 0;
        while (inner_counter < line_counter) {
            string += "#"
            inner_counter++;
        }
        print(string)
        line_counter++;
    }
}

2.4

function exponent(val, exp) {
  product = 1;
  for (var i = 0; i < exp; i++) {
    product *= val;
  }
  return product;
}

exponent(2, 10) == 1024

function triangle(lines) {
  for (var i = 1; i <= lines; i++) {
    var string = ""
    for (var j = 0; j < i; j++) {
      string += "#"
    }
    print(string);
  }
}
triangle(10);
#
##
###
####
#####
######
#######
########
#########
##########

2.5

var result = Number(prompt("What's the value of 2+2?"));
if (result == 4) {
    alert("Excellent");
}
else if (result == 3 || result == 5) {
    alert("Almost");
}
else {
    alert("Idiot.");
}

2.6

while (true) {
    var result = Number(prompt("What's the value of 2+2?"));
    if (result == 4) {
        alert("Excellent");
        break;
    }
    else if (result == 3 || result == 5) {
        alert("Almost");
    }
    else {
        alert("Idiot.");
    }
}

2.

var name = prompt("What's your name?") || "Guest";

This is an example of using the OR binary op to return the second operand if the first is a Falsey value (e.g. the empty string). This allows you to provide sensible defaults

We can use the && as a guard against null values. For instance, if we want to invoke a method on an object, but not if it’s null, we could do

var result = X && X.someMethod()

since the && will only evaluate the second operand if the first is not a Falsey value (e.g. null), we are safe from executing undefined methods.

 

/*#p2pu-Jan2011-javascript101*/