js-lib

Monday, February 28, 2011

JavaScript101 - Week 5 (Track 1)

  1. Why is it better to use either trickling or bubbling of events? Why not just give the event to the node on which it was invoked?
  2. Let's say there is an event you want to handle for dozens of similar elements on the page. Without bubbling, you would have to wire the same event handler to every single one of those elements. It's better to enclose the elemements in a parent node and assign the event handler to the parent; the handler will then respond to the event as it bubbles up from each child element.

  3. Can you think of one situation where you would want to prevent the browser from submitting a form after a user has clicked on the 'submit' button? How would you achieve this?
  4. Form data should be validated on the client side before submitting is allowed. I would write a validateForm() function and set the sumit button as follows: onclick="return validateForm()"


Enter how many numbers you want to add
(between 2 and 10):


 

Saturday, February 19, 2011

JavaScript101 - Week 4 (Track 1)

  1. There were two key innovations to the original (fetch-parse-flow-paint) linear workflow that the Mosaic browser used to render web pages. One allowed for a perception of faster rendering, and the other allowed for us to use AJAX. Explain both?
  2. The perception of faster rendering was achieved with placeholders in the document flow for large, slow loading images; meanwhile, fetching and rendering of the other content continues. As the slower elements are finally retrieved, the flow and paint steps are repeated multiple times in order to put all elements in their respective places.

    The other innovation was the use of scripting to dynamically manipulate the DOM. Client-side events can now cause functions to be invoked, which may in turn re-render the content in the window.

  3. What are the roles of 'name' and 'id' attributes in HTML tags? What is an appropriate use of both?
  4. The name attribute can be used to identify a window or frame, or some value in form data (in addition to name, form elements have a value attribute — a name-value pair). For example, a single name would be used to correlate several radio buttons to one option group. The id attribute is used to uniquely identify a single element, so as to apply a style to it or possibly access its content.

  5. Which pointers does each node in the DOM tree typically have?
  6. Each node has a pointer to its text node, parent, firstChild, lastChild, nextSibling, and previousSibling.

  7. Given a node object from a DOM tree, how do we determine if it is a text node or a regular node?
  8. Use either of the properties nodeName or nodeType.

    For a text node, the nodeName property equals '#text' and nodeType equals '3.'

    Some additional notes about DOM nodes at w3schools here and here:

    Text is Always Stored in Text Nodes
    A common error in DOM processing is to expect an element node to contain text. However, the text of an element node is stored in a text node. In this example: <year>2005</year>, the element node <year>, holds a text node with the value "2005". "2005" is not the value of the <year> element!

    Is this a text node?  

 


function demo4(){
  var count = countTextNodes(document.getElementById("theDoc"));
  var targetNode = document.MONDOSEARCHFORM.parentNode; //Chose this because I want to print the output above the rest of the page
  var newSpan = document.createElement("span");
  var myButton = document.createElement("span");
  newSpan.innerHTML = "<span id='newSpan' style='font-size:1.5em;'> The document below has " + count + " text nodes! </span>";
  myButton.innerHTML = "<input type='submit' value='Bold text' onclick='document.getElementById(\"newSpan\").setAttribute(\"style\", \"font-size:1.5em; font-weight:bold;\");'>";
  targetNode.replaceChild(newSpan, targetNode.firstChild); //Put my stuff first!
  newSpan.appendChild(myButton);
}

function countTextNodes(topNode){
  var count=0;
  walkTheDOM(topNode, function (node) {
    if(node.nodeType==3) count++;
  });
  return count;
}
 
function walkTheDOM (node, func) {
  func(node);
  node = node.firstChild;
  while (node) {
 walkTheDOM(node, func); /* walkTheDOM recursively for successive firstChild nodes until no more children. It seems that
                            the loop halts and you never get back here, but...***/
 node = node.nextSibling; /* Eventually, control does resume at this line. Continue with the sibling and its children... */
  }
}

Click this button for the homework demonstration:

 

Thursday, February 17, 2011

Week 3 (Track 1)

Exercise 6.1

Well, this was certainly a challenging first assignment! Was I supposed to write a function that counts zero values in an array of numbers? I understood the task to be counting zeros in numbers like .008 and 500.
I came up with something that implements forEach directly — I did not use reduce. However, I did gain a better understanding of the textbook code by the end of the chapter.
function count(array, findChar){
   var counter = 0;
 //Check each character in the array against the findChar
   forEach(array.join('').toString(), function(chr){
    if(chr == findChar){counter++;}
   });
   return counter;
}
Find the character

in this array (comma-delimited):  


And here is my slightly different take on the countZeroes function, using reduce:
function countZeroes(array){
   function isZero(base, element){
  return element==0 ? base + 1 : base;
   }
   alert(reduce(isZero, 0, array));
}
Zero values in this array (comma-delimited):


   

Exercise 6.2

//processParagraph calls splitParagraph, which returns an array of fragments

 function processParagraph(paragraph) {
   var header = 0;
   while (paragraph.charAt(0) == "%") {
  paragraph = paragraph.slice(1);
  header++;
   }
   return {type: (header == 0 ? "p" : "h" + header),
        content: splitParagraph(paragraph)};
 }

Exercise 6.4

//This implementation allows for additional attributes

function image(src, attributes) {
  if(attributes) attributes.src = src;
  else attributes = {src: src};
  return tag("img", '', attributes);
}


The Print Book button encompasses all work from the Chapter 6 exercises:



Clicky!




  1. In Javascript, functions are first class objects. What does it mean to be a first class object?
  2. In Javascript, functions inherit from Object and may contain key-value pairs, as well as other functions, as members. A function may be passed, returned, or stored in variables just like any other value.

  3. Functions and variables share the same namespace. What does this mean and what important implication does this have?
  4. In the lecture, Crockford explains that the function statement is shorthand for the process of creating a variable and assigning a function as its value; i.e., function foo(){}  expands to   var foo = function foo(){}; He then goes a step further and states that the language permits having functions and variables with the same name in one namespace. This confused me at first, until I realized that the same principle applies to having several block variables named i throughout a program. This is harmless as long as the variables are very narrow in scope and do not conflict with one another. I can think of no other scenario where having multiple variables with the same name is desirable or something you would do purposely. As I have come to learn, the following code is not workable:
    function myName(){ return "Darryl"; }
     var myName = "Banks";
     function test(){
        try{
      alert(myName());
      alert(myName);
        } catch(e){alert(e.message);}
     }
    In the code above, the function assigned to myName on the first line is overwritten with a new value on the second line. The following exception is thrown (by alert(myName())) because the value in myName is now "Banks":

       

  5. Douglas Crockford equates Javascript functions with Lambdas, and also mentions that they are a secure construct. Can you do some research and reflect on what he means by 'secure construct'?
  6. Nope, I have no idea. I had never before heard of a "power-construct," nor a secure construct. I hope this will be covered in a subsequent lecture.

  7. Can you explain the concept of a closure.
  8. An inner function is a function that is defined inside another function. By closure, we mean that the inner function has access to all of the variables and parameters of its parent function, even after the parent function has returned. This can be utilized for asyncronous processing in AJAX.

  9. What is the difference between a function and a method?
  10. A method is a function defined within an object. A method may be invoked using the Object.method syntax.

  11. In Javascript there is no implicit type checking of arguments passed to functions. This could lead to bugs if programmers are not careful about what they pass to functions. If you create a function, how would you protect it from well meaning but careless programmers?
  12. Manual checking of arguments. Conditionals and conversion/parsing functions.

  13. Javascript functions have implicit access to something called this. this points to different things depending on how the function was created. Can you explain why we need this, and what it represents in different type of functions.
  14. The special parameter called this refers to the object that contains the current function. By default, it refers to the global object (within the DOM context, the global object is the document's window). Inside an object's scope, this refers to the containing object.

  15. Why doesn't Javascript have a cast operator?
  16. Casting is unnecessary in such a loosely typed language. Besides the string and number types, values will take the form of functions and objects. JavaScript trades type safety for dynamism and expressiveness.

  17. What is reflection and why is it easy in Javascript (you may need to do research to answer this question)?
  18. Reflection is the aspect that allows a value or object to expose its type at runtime. I know of two keywords that facilitate type checking in Javascript: typeof and instanceof

Friday, February 11, 2011

JavaScript 101 - Week 2 (Track 1)



 

Exercise 3.1

function absolute(num){
if (num == parseFloat(num))
  return num < 0 ? -num : num; }
 

Exercise 3.2

function greaterThan(testValue){
return function(number){
return number > testValue;
};
}
var greaterThanTen = greaterThan(10);


Why do languages provide the switch statement, when we can achieve the same thing with multiple if... elseif statements? Show one example of how you might use the switch statement.


The switch statement is more convenient and succinct than multiple elseif statements (notwithstanding those pesky break statements!)
Example:
var state;
var abbr = 'NC';
switch(abbr)
{
   case 'NC':
    state = 'North Carolina';
     break;
   case 'VA':
     state = 'Virginia';
     break;
    case 'FL':
     state = 'Florida';
     break;
 }
show(state);

What is a pure function? Is the function show() provided in Eloquent Javascript a pure function?


A pure function is one which always returns the same value when given the same arguments, and never has side effects. The show() function is not pure because it produces a side effect.

What do we mean when we say a variable in a function is shadowing a top level variable?


A function may access variables which are defined outside of the function's scope. A top-level variable would be one such variable.

A recursive function must have some sort of an end condition. Why would we get a "out of stack space" error message if a recursive function does not have an end condition?


Without an end condition, a recursive function will run in an infinite loop. The repeated function calls would certainly overflow the call stack.

Reflect about the difference between object inheritance and class inheritance


JavaScript is a loosely typed language with no classes, so objects do not inherit from predefined classes.  Instead, new objects can be made that are similar to existing objects, and then customized.  Object customization requires less work than defining classes, and less overhead, too.

What is object augmentation, and how do we do it?


Object augmentation is the addition of new members to existing object instances. It is accomplished through simple assignment.

There is a way to add a method to String, such as any new String we create will have that augmented method (this is a bit different from object augmentation). How would you do this?


By using “linkage” new String objects can be created which will have all methods included in the original String. Linkage is achieved through the object() function, as in:
var newString = object(String);

What is garbage collection?


Garbage collection is a means of reclaiming unused computer memory once object references are no longer needed.

What is the difference between an array and an object?


Array inherits from Object, but it also has some unique native members of its own, e.g. concat(), sort() and splice(). A new empty array can be declared using the literal []. The Array links to Array.prototype

 

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.