js-lib

Sunday, January 30, 2011

JavaScript 101 - Week 1

1. 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 think of Java as a compiled platform for running applications. To embed all those APIs in the browser would be overkill for the most general uses of Web clients (rendering pages, form interaction, and making HTTP requests).  JavaScript, however, is a text based, interpreted, load-and-go language.  It was intended to be embedded in Web pages.


2. When parsing a String into a number using the parseInt() method, we are advised to always provide the radix. Why is it so strongly recommended?


There are other numeral systems besides base-10; an expression with a leading zero could be interpreted as an octal number.

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


The data type system allows you to specify the nature or intended purpose of a particular value.  For example, the Boolean type allows checking for a certain condition, and the Number type is for doing math.  Take the expression'32': is it intended to be used in a mathematical operation, or is it meant to be two ASCII characters displayed in output?

4. 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? 

Floating point arithmetic can only give you approximations for decimal fractions--a number may be represented only with a finite number of bits, and the computer relies on scientific notation.  This imprecision would definitely be a problem when dealing with money.


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

Yes.

Lol, the result is due to the order of operations; multiplication and division take precedence before addition and subraction.

6. What does typeof 4.5 do, and why does typeof (typeof 4.5) return "string" ?

The typeof operator produces a string value naming the type of the value you give it.

Create an example that shows a valid use of the 'guard' and 'default' operators in Javascript

Guard example:   result = user.activeFlag && user.subscriptions

Default example: thumbnail = user.avatar || 'default.png'
...

As for the Chapter 2 exercises--those answers were given in the text. My answers were essentially the same, so I am not including them here.