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?
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.
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?
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):
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?
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.
What are the roles of 'name' and 'id' attributes in HTML tags? What is an appropriate use of both?
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.
Which pointers does each node in the DOM tree typically have?
Each node has a pointer to its text node, parent, firstChild, lastChild, nextSibling, and previousSibling.
Given a node object from a DOM tree, how do we determine if it is a text node or a regular node?
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... */
}
}
My original reasons, when I designed the site in 1995, were as follows:
Download times rule the Web, and since many users still don't have broadband, Web pages can be no more than 6 KB if they are to download in one second which is the required response time for hypertext navigation. Users do not keep their attention on the page if downloading exceeds 10 seconds, corresponding to 60 KB at modem speed. Keeping below these size limits rules out most graphics.
I am not a visual designer, so my graphics would look crummy anyway. Since this website is created by myself (and not by a multidisciplinary team as I always recommend for large sites) I didn't want to spend money to hire an artist.
These arguments are still relevant, even though most users now have broadband access and can accommodate a few images. Indeed, I have started using screenshot and charts in my articles from time to time.
I did have to add a small glyph to the navigation bar to emphasize the meaning of the hierarchy nesting. My original design used a simple colon to separate the levels, but some users thought that the colons indicated alternative choices on the same level (and not a progressively deeper nesting of options, as intended). The arrows seem to be slightly easier to understand as an indication of moving deeper and deeper into the site.
Before: use of a colon as hierarchy separator
After: use of an arrow as hierarchy separator
(Update 2007: note that the current recommendation for the breadcrumb separator is to simply use a > [greater-than sign]. Users are now so accustomed to breadcrumbs that there's no need for the added symbolism provided by an arrow.)
I have used Pair since 1996 for various smaller projects and been very satisfied, and since 2005 I am hosting the two high-traffic sites there as well. Good performance and almost no downtime.
One benefit of the small number of graphics on this site is that I can serve a quarter million unique users per month and about 50 GB/month data transfer with a relatively cheap Web hosting account that covers both sites for $75/month. The cost of running the sites comes to 0.02 cents per user or 0.005 cents per pageview served.
Even though I'm happy with Pair Networks, and even though they offer their own domain hosting service, I still stick with GoDaddy for domain hosting. This is to reserve the possibility of switching my hosting to another service at a moment's notice if Pair ever degrades its service the way every other hosting company I've ever been with has eventually done. (To the credit of Pair's founders, they have not sold out to a big company with bad service, but one never knows whether that could happen.) It's safest to separate site hosting and domain names, and maintain the two at different companies.
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;
}
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));
}
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)};
}
The Print Book button encompasses all work from the Chapter 6 exercises:
Clicky!
In Javascript, functions are first class objects. What does it mean to be a first class object?
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.
Functions and variables share the same namespace. What does this mean and what important implication does this have?
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":
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'?
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.
Can you explain the concept of a closure.
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.
What is the difference between a function and a method?
A method is a function defined within an object. A method may be invoked using the Object.method syntax.
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?
Manual checking of arguments. Conditionals and conversion/parsing functions.
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.
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.
Why doesn't Javascript have a cast operator?
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.
What is reflection and why is it easy in Javascript (you may need to do research to answer this question)?
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
% The Book of Programming%% The Two AspectsBelow the surface of the machine, the program moves. Without effort,
it expands and contracts. In great harmony, electrons scatter and
regroup. The forms on the monitor are but ripples on the water. The
essence stays invisibly below.When the creators built the machine, they put in the processor and the
memory. From these arise the two aspects of the program.The aspect of the processor is the active substance. It is called
Control. The aspect of the memory is the passive substance. It is
called Data.Data is made of merely bits, yet it takes complex forms. Control
consists only of simple instructions, yet it performs difficult
tasks. From the small and trivial, the large and complex arise.The program source is Data. Control arises from it. The Control
proceeds to create new Data. The one is born from the other, the
other is useless without the one. This is the harmonious cycle of
Data and Control.Of themselves, Data and Control are without structure. The programmers
of old moulded their programs out of this raw substance. Over time,
the amorphous Data has crystallised into data types, and the chaotic
Control was restricted into control structures and functions.%% Short SayingsWhen a student asked Fu-Tzu about the nature of the cycle of Data and
Control, Fu-Tzu replied 'Think of a compiler, compiling itself.'A student asked 'The programmers of old used only simple machines and
no programming languages, yet they made beautiful programs. Why do we
use complicated machines and programming languages?'. Fu-Tzu replied
'The builders of old used only sticks and clay, yet they made
beautiful huts.'A hermit spent ten years writing a program. 'My program can compute
the motion of the stars on a 286-computer running MS DOS', he proudly
announced. 'Nobody owns a 286-computer or uses MS DOS anymore.',
Fu-Tzu responded.Fu-Tzu had written a small program that was full of global state and
dubious shortcuts. Reading it, a student asked 'You warned us against
these techniques, yet I find them in your program. How can this be?'
Fu-Tzu said 'There is no need to fetch a water hose when the house is
not on fire.'{This is not to be read as an encouragement of sloppy
programming, but rather as a warning against neurotic adherence to
rules of thumb.} %% WisdomA student was complaining about digital numbers. 'When I take the root
of two and then square it again, the result is already inaccurate!'.
Overhearing him, Fu-Tzu laughed. 'Here is a sheet of paper. Write down
the precise value of the square root of two for me.'Fu-Tzu said 'When you cut against the grain of the wood, much strength
is needed. When you program against the grain of a problem, much code
is needed.'Tzu-li and Tzu-ssu were boasting about the size of their latest
programs. 'Two-hundred thousand lines', said Tzu-li, 'not counting
comments!'. 'Psah', said Tzu-ssu, 'mine is almost a *million* lines
already.' Fu-Tzu said 'My best program has five hundred lines.'
Hearing this, Tzu-li and Tzu-ssu were enlightened.A student had been sitting motionless behind his computer for hours,
frowning darkly. He was trying to write a beautiful solution to a
difficult problem, but could not find the right approach. Fu-Tzu hit
him on the back of his head and shouted '*Type something!*' The student
started writing an ugly solution. After he had finished, he suddenly
understood the beautiful solution.%% ProgressionA beginning programmer writes his programs like an ant builds her
hill, one piece at a time, without thought for the bigger structure.
His programs will be like loose sand. They may stand for a while, but
growing too big they fall apart{Referring to the danger of internal
inconsistency and duplicated structure in unorganised code.}.Realising this problem, the programmer will start to spend a lot of
time thinking about structure. His programs will be rigidly
structured, like rock sculptures. They are solid, but when they must
change, violence must be done to them{Referring to the fact that
structure tends to put restrictions on the evolution of a program.}. The master programmer knows when to apply structure and when to leave
things in their simple form. His programs are like clay, solid yet
malleable.%% LanguageWhen a programming language is created, it is given syntax and
semantics. The syntax describes the form of the program, the semantics
describe the function. When the syntax is beautiful and the semantics
are clear, the program will be like a stately tree. When the syntax is
clumsy and the semantics confusing, the program will be like a bramble
bush.Tzu-ssu was asked to write a program in the language called Java,
which takes a very primitive approach to functions. Every morning, as
he sat down in front of his computer, he started complaining. All day
he cursed, blaming the language for all that went wrong. Fu-Tzu
listened for a while, and then reproached him, saying 'Every language
has its own way. Follow its form, do not try to program as if you
were using another language.'
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
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