Introduction to Javascript for programmers

I signed up for participation in the Introduction To Javascript (for programmers) course on diycomputerscience.com

In week 1, we are supposed to watch a video which explains the basic capabilities of Javascript in about 17 minutes, and then do 2 learning activities. The first week seems like a relatively low pressure week.

I will be blogging my notes for every video on this blog, and will also publish assignments and activities here.

Filed under  //   diycs_sg2   javascript  

Javascript 101 - HTML DOM

The 'document' object is the root object of the DOM, it has a single child node which is the HTML node. 

Every object has pointers to it's child nodes(childNodes[i], firstChild, lastChild), parent node (parentNode), and siblings (nextSibling, previousSibling).

The nodeName property of the node tells us the type of the node. So the nodeName for the HTML node will be "HTML". The nodeName for a text node is "#text", and for the document node is "#document".

document.documentElement refers to the HTML node

To directly access an object in the DOM by it's id, we can use 

document.getElementById(id);

 

We can also get objects by tag name. This will be useful if for instance we want to get all paragraph objects. This method can also be called on a specific node, to return all elements within that node.

document.getElementsByTagName("p");

 

We can change the value of a text node by setting the new value to it's nodeValue property. 

We can even change the values of node attributes.

node.setAttribute("align", newval);

 

We can even insert elements. First we must create an element and then insert it in the right place.

var x = document.createElement("HR"); document.getElementById('inserthere').appendChild(x);

 

We can even remove nodes. A node has to be removed through it's parent node.

var node = document.getElementById("inserthere"); node.parentNode.removeChild(node);

 

 

 

Document elements often have attributes. One such attribute 'id' is used to uniquely identify an element in a tree of elements. Earlier the 'name' element could also be used for the same purpose, but this is no longer true. The name element's true purpose is to be used in forms to represent values of various form elements. It can also be used to give names to windows, and frames.

node.className is the property which we can use to access the class attribute of a node in the HTML DOM.

Filed under  //   javascript  

Javascript 101 - Week 3 Assigments

6.1 Write a function countZeroes, which takes an array of numbers as its argument and returns the amount of zeroes that occur in it. Use reduce.

Then, write the higher-order function count, which takes an array and a test function as arguments, and returns the amount of elements in the array for which the test function returned true. Re-implement countZeroes using this function.

6.2 Write a function processParagraph that, when given a paragraph string as its argument, checks whether this paragraph is a header. If it is, it strips of the '%' characters and counts their number. Then, it returns an object with two properties, content, which contains the text inside the paragraph, and type, which contains the tag that this paragraph must be wrapped in, "p" for regular paragraphs, "h1" for headers with one '%', and "hX" for headers with X '%' characters.

Remember that strings have a charAt method that can be used to look at a specific character inside them.

6.3 Build a function splitParagraph which, given a paragraph string, returns an array of paragraph fragments. Think of a good way to represent the fragments.

The method indexOf, which searches for a character or sub-string in a string and returns its position, or -1 if not found, will probably be useful in some way here.

This is a tricky algorithm, and there are many not-quite-correct or way-too-long ways to describe it. If you run into problems, just think about it for a minute. Try to write inner functions that perform the smaller actions that make up the algorithm.

6.4 Looking back at the example HTML document if necessary, write an image function which, when given the location of an image file, will create an img HTML element.

Filed under  //   javascript  

Javascript 101 - Week 3 Reflections

1. In Javascript, functions are first class objects. What does it mean to be a first class object?
Javascript functions are called first class objects because they can be used anywhere an object can be used. They can be held in variables, and they can be passed to other functions as a parameter. Over and above this Javascript functions are actually objects and can contain name:value properties just like any other object in Javascript. Unrelated to the question, but I would like to state another important fact about Javascript functions, which is that they create a special scope called a lambda or a closure.
2. Functions and variables share the same namespace. What does this mean and what important implication does this have?
In Javascript, functions and variables are all created in the same namespace. What this means is they could collide with one another. I would like to illustrate this concept with a few examples. In the examples below, the webpage contains a button, which when clicked evaluates the value of the variable 'f' and prints the result in a span tag in the webpage.

The image below shows that we only have a variable f which holds the number 3. This is what gets printed when we click the button.

 

Onlyvar

The image below shows that we only have a function f. When we click the button, the body if the function is printed.

Onlyfunc

The image below shows that we have both a function f and a variable f. However, when we click the button, the value of the variable is printed. We will get the same result even if the order of the function and the variable holding the number are reversed. I am not sure if we should depend on the result, because it may also be a browser thing. This code was run on Firefox, and running it on another browser may yield a different result. However, it does point to the fact that we have to be careful and make sure that function names do not collide with variable names.

Varandfunc

3. 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'?
Lambdas in Javascript have very well defined scoping rules for what they can access. This is what Douglas Crockford means by secure construct. I also asked this question on StackOverflow, and here is the thread with two answers.
4. Can you explain the concept of a closure.
A closure is an inner function, which is a function defined within another function. This inner function has access to all the variables and input parameters of the outer function, and it continues having this access even after the outer function has returned. The 'greaterThan' function shown below is a closure. The fact that the variables of an outer function continue to exist even after it has exited is very confusing. It may make it slightly easier to remember this concept if we understand that Javascript functions, beyond fulfilling some functionality in the code, are also responsible for creating a scope. This scope may continue to exist after the function has returned, if it has any number of inner functions which have access to that scope.
5. What is the difference between a function and a method?
When a function is encapsulated within an object, we call it a method.
6. 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?
I first perform a count on the number of arguments by checking arguments.length, then I would do a typeof check on all the arguments to ensure that they are of the correct type.

7. 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.
'this' is an implicit reference which is given to all functions in Javascript by the runtime. 'this' can point to different things based on the context of the function. If the function in question is a method which belongs to an object then 'this' will be a reference to that object. If the function does not belog to any object then 'this' will point to the global object. Inner functions also have a 'this', but unfortunately (because it is incorrect) within inner functions 'this' also points to the global object. When a function is created using the new Function() operator, 'this' points to the function object.
8. Why doesn't Javascript have a cast operator?
The cast operator is usually needed in languages which are statically typed. In such languages we may need the cast operator to convert an object's type to the type of the variable we are assigning it to. However, because Javascript is a dynamically typed language, it does not need a cast operator.
9. What is reflection and why is it easy in Javascript (you may need to do research to answer this question)?
Reflection is the act of getting details (such as properties, methods, etc) of an object at runtime, given a reference to the object. In Javascript reflection is easy because objects are a collection of name:value pairs and we can get all the information we want simply by getting the names and values.
Filed under  //   javascript  

Javascript 101 - Week 2 Assignments

Embedding my programming assignments from week 2 of the Javascript 101 course.
Assignment 1:

Assignment 2:

Assignment 3:

Assignment 4:

Filed under  //   javascript  

Javascript 101 - Week 2 Reflections

1. 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.

A switch statement is a more readable way to accomplish multiple if...elseif...else statements. An example of usage of switch statements is perhaps code that reads in an answer from a multiple choice quiz.

function answer(choice) {

    switch(choice) {

        case 'a':

            alert('wrong answer');

            break;

        case 'b':

            alert('wrong answer');

            break;

        case 'c':

            alert('right answer');

            break;

        case 'd':

            alert('wrong answer');

            break;

        default:

            alert('This choice was not provided... how did you get it?');

            break;

    }

}

answer('a');

Note that the break statement at the end of every case statement is very important. Without it flow of execution will go into the next case, even though it does not match. In my opinion, this is a disadvantage when we compare the switch with if...elseif...else statements. Javascript could have done away with the default statement, but they chose not to. 

 

 

2. What is encapsulation, and what do functions encapsulate?

In my opinion encapsulation is bundling related things together into one unit. In Javascript a function is a unit of code with related variables which accomplishes something. A weel designed function follows the Single Responsibility Principle. 

 

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

A pure function is one which always produces the same result whenever it is invoked, and which does not have any side effects. The function 'show()' in Eloquent Javascript isnot a pure function because it does it's work through a side effect.

 

4. What do we mean when we say a variable in a function is shadowing a top level variable?
Javascript has the notion of scope. What this means is that a variable defined in some place is visible within it's scope. A variable which is declared in a function is visible only in that function. Also a variable declared within a function can have the same name as a top level variable outside of the function. When a variable in a function has the same name as a top level variable, we say that it is shadowing the top level variable. The function below shows this with an example. The value shown by the alert popup will be 9.
var i = 5;
function f() {
  //the variable i declared below is shadowing the top level variable i
  var i = 9;
  alert(i);
}

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

A recursive function is a function which calls itself. If a function calls itself, then in that invocation, it will again call itself, and so on. This will result in an infinite series of calls to itself. When a function is invoked a frame gets created for it on the stack. If it is invoked infinitely then the runtime will attempt to alloate an infinite number if frames for it on the stack. At some point of time, the runtime will run out of stack space and give us the error "out of stack space".

 

6. Reflect about the difference between object inheritance and class inheritance

In programming languages which use classes, a class is like a blueprint. When an object of that class is created it contains everything which the blueprint contains. Classes define inheritance relationships, such that when an object is created it contains everything which is contained in it's class, as well as superclasses. Even though there are some rules which govern who can see what, essentially everything is contained within the same object. 

However, object inheritance is different. There are no classes or blueprints. An object is simply a collection of name:value pairs. When an object inherits from another object, it is linked with it's parent. When a property of the child object is looked up, and if the child does not contain the property, then it's parent object will be looked up to yield that property. We can establish any level of inheritance. The object at the very top of the inheritance chain is Object.prototype

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

At runtime we can dynamically add properties to an object. This is known as object augmentation. The example below shows an array object. We can add a method to it at runtime simply by assigning the function as a member of the object.

var someArr = [1, 2, 3];

someArr.sum = function() {

    var theSum = 0;

    for(var i=0; i<this.length; i++) {

        if(this.length instanceof Number) {

            theSum += this.length;

        }

    }

}

alert(someArr.sum());

If we want this method to be in all arrays we create, then we can add it to Array.prototype

Array.prototype.sum = function() {

    var theSum = 0;

    for(var i=0; i<this.length; i++) {

        if(this.length instanceof Number) {

            theSum += this.length;

        }

    }

}

var anotherArray = [4, 't', 5, 6];

alert(anotherArray.sum());

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

We can add the function to String.prototype. In answer 7, I have added the sum() function to Array.prototype. Similarly, we can add any function to String.prototype, and it will be in every String that is created in the system within that environment.

9. What is garbage collection?

In certain languages such as C and C++, prgrammers have to explicitly allocate and deallocate memory for their objects and data structures. However, many modern languages have what is known as Garbage Collection to relieve the programmer from this tedious and buggy filled task. In such languages the runtime has a garbage collector which figures out which objects are not being referenced anymore (hence not in use) and it automatically reclaims memory from those objects.

10. What is the difference between an array and an object?

An array is a special type of object. It's parent is Array.prototype and it has been enhanced with certain methods and properties which give it the array nature. For example an array always has the length property, and a few methods such as splice(),... etc. The subscripts which we use in an array (under the hoods) are actually converted to Strings and stored as names in the object. The example below shows an array and how it actually looks like in the object.

var animals = ['cat', 'dog', 'horse'];

In the actual array object looks like this

'0':'cat',

'1':'dog',

'2':'horse'

Filed under  //   javascript  

Javascript Arrays

I finished reading the chapter in Arrays form Eloquent javascript. My notes:

  • arrays have methods (concat, join, push, pop, slice, sort, splice)
  • Deleting members from an array is tricky business, because they can leave a hold. Use splice() after deleting members of an array.
  • Array inherits from object, indexes converted into strings, so a regular array is also an associative array
  • Arrays have a length member which is 1 more than the highest integer subscript.
  • Array length does not need to be declared... because it does not matter
  • Do not use 'for in' with arrays... why?
  • Array literals

          var myArr = [100, 200, 5000];
          also myList[1000] = "something";

  • There are several ways of creating an array, [] is the most preferred
  • Arrays get linked to Array.prototype?
  • How do we determine if an object is an array?

          value.constructor == Array
          value instanceof Array
          Neither of these work if the val came from another frame...

  • Do not use an Array as a prototype because the resulting object will not be an array. Instead either augment one particicular array object, or augment Array.prototype

 

Filed under  //   javascript  

Javascript Objects

  • Objects can contain data and methods, and objects can inherit from other objects.
  • JS objects are a collection of name value pairs, where names are strings (or just names), and the value can be any expression, or even an object literal.
  • We can use the dot . notation as well as the [] notation to access members. Reserved words can be accessed only with the [] notation, and they have to be strings.
  • We can also use maker functions which take params and return an object
  • Nested objects are also possible with object literals as well as maker functions.
  • The last property in the object cannot have a trailing comma
  • The video says that an Exception object must have three properties
  • We can add functions or properties to any object... just augment the object with what is desired
  • An object can inherit from any other object. Every object has a link to another object (at the top of the chain is Object.prototype)

         new Object()
         var newObj = object(existingObj);
         var newObj = {} - This is preferred

         Similarly Exceptions can also be created in multiple ways:

        throw new Error(reason);

        throw {

           name: exceptionName,

           message: reason

        };

  • Both objects can contain the same property...
  • In JS new objects are made from similar objects and then customized...(prototypal inheritance)
  • What happens to the new object if the old object is set to undefined?  The link is not broken because the variable is set to undefined and not the object... but the old object can be changed... in which case we cannot access that property... 
  • Just like properties can be augmented, properties can be also deleted

          delete myObj[name]
          delete myObj.name

  • Circular linkages? Will not happen.
  • JS has Garbage collection.
  • No equals() method for logical equality, only ==, or === for references
  • Objects are always passed by reference
  • Objects as well as prototypes can be augmented
  • Object.prototype is the object which is the last in the linkage (similar to Java's Object class)
  • Can we create our own something.prototype? which holds all the blog posts you have
  • In functions, we can simulate named parameters by using a single object literal instead of n parameters to a function.
  • Objects are always passed by reference and never by value.
  • JS does not have the notion of logical equality.
Filed under  //   javascript  

Javascript statements

#p2pu-Jan2011-javascript101

In the first part [00:00 - 08:00 mins] of this video, Douglas Crockford talks about statements in Javascript. I have blogged my notes below:

JS has labelled breaks, nice to know.

The 'for' statement can be used with arrays (as expected), but it can be used with objects also. In the latter case it iterates through all the keys in an object, and it's ancestors.

for() {
  if(object.hasOwnProperty(name)) {
   
  }
}

As most other langauges Javascript also has a switch statement, however the switch value does not need to be a number, and case values can be expressions.

We can throw and catch Exceptions in Javascript. Since JS does not have classes, there is just one Exception (which is of type Object). The Javascript engine can throw the following Exception names (all of type Object) (Error, EvalError, RangeError, SyntaxError, TypeError, URIError)
try {} catch(e){}

Do not use the with statement...

Javascript supports functions. All functions start with the function keyword.
function name(parameters) {

}

Javascript uses the keyword var to declare variables.
var student;
If a var is not initialized then the variable will be set to undefined. Javascript has implicit global variables.

In JS blocks do not have scope, only function scope. We can declare a variable anywhere in a fuction (even after it's use?). Remember if we declare a variable twice, it gets created only once, and no error is generated.

Every function in Javascrpt returns something. If we do not explicitly return anything, then 'undefined' will be returned.

Javascript's switch statement is less limiting than C or C++. In Javascript the value in the switch part is not restricted to numbers. It can contain numbers, Strings, or any object for that matter. The case statements are also not limited to having only constants. They can even contain expressions.

Filed under  //   javascript  

Javascript 101 - Week 1 Programming Assignments

Exercise 2.1 - Is the statement below true?

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


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

 

Exercise 2.2:

Use the techniques shown so far to write a program that calculates and shows the value of 210 (2 to the 10th power). You are, obviously, not allowed to use a cheap trick like just writing 2 * 2 * ....

If you are having trouble with this, try to see it in terms of the even-numbers example. The program must perform an action a certain amount of times. A counter variable with a while loop can be used for that. Instead of printing the counter, the program must multiply something by 2. This something should be another variable, in which the result value is built up.

Don't worry if you don't quite see how this would work yet. Even if you perfectly understand all the techniques this chapter covers, it can be hard to apply them to a specific problem. Reading and writing code will help develop a feeling for this, so study the solution, and try the next exercise.

Answer:
var count = 0;
var result = 1;
while(count < 10) {
  result = result * 2;
  count += 1;
}
print(result);

 

Exercise 2.3:

With some slight modifications, the solution to the previous exercise can be made to draw a triangle. And when I say 'draw a triangle' I mean 'print out some text that almost looks like a triangle when you squint'.

Print out ten lines. On the first line there is one '#' character. On the second there are two. And so on.

How does one get a string with X '#' characters in it? One way is to build it every time it is needed with an 'inner loop' ― a loop inside a loop. A simpler way is to reuse the string that the previous iteration of the loop used, and add one character to it.
 

Answer:
var count = 0;
var trianglePart = '#';
while(count < 10) {
  print(trianglePart);
  trianglePart += '#';
  count += 1;
}

 

Exercise 2.4:

Rewrite the solutions of the previous two exercises to use for instead of while.
 

Answer:
var trianglePart = '#';
for(var i=0; i < 10; i++) {
  print(trianglePart);
  trianglePart += '#';
}

 

Exercise 2.5:

Write a program to ask yourself, using prompt, what the value of 2 + 2 is. If the answer is "4", use alert to say something praising. If it is "3" or "5", say "Almost!". In other cases, say something mean.
 

Answer:
var question = "2 + 2 = ?";
var praisingResponse = "You have awesome math skills!";
var almostResponse = "Almost";
var rudeResponse = "You need to go back to Kindergarten";

var answer = prompt(question);
show(answer);
if(answer == "4")
  print(praisingResponse);
else if(answer == "3" || answer == "5")
  print(almostResponse);
else
  print(rudeResponse);

 

Exercise 2.6:

Add a while and optionally a break to your solution for the previous exercise, so that it keeps repeating the question until a correct answer is given.

Note that while (true) ... can be used to create a loop that does not end on its own account. This is a bit silly, you ask the program to loop as long as true is true, but it is a useful trick.


Answer:
var question = "2 + 2 = ?";
var praisingResponse = "You have awesome math skills!";
var almostResponse = "Almost";
var rudeResponse = "You need to go back to Kindergarten";

while(true) {
  var answer = prompt(question);
  show(answer);
  if(answer == null) {
    print("Quitter!");
    break;
  }
  else if(answer == "4") {
    print(praisingResponse);
    break;
  }
  else if(answer == "3" || answer == "5")
    print(almostResponse);
  else
    print(rudeResponse);
}

Filed under  //   javascript  

About

I am an freelance software developer and trainer. I am also interested in open education and social learning. This Posterous is my experiment in getting an equivalent of a masters education in Computer Science using open courseware and social learning.