Wednesday, February 23, 2011

Week 3-Homework and Assignments

1. In Javascript, functions are first class objects. What does it mean to be a first class object?
Answer:  Functions are first class objects. This means they have all the properties of a normal JS object: they can contain name/value pairs, can be passed, returned or stored just like objects.

2. Functions and variables share the same namespace. What does this mean and what important implication does this have? 
Answer:  According to Wikipedia, "a namespace is a container that provides context for the identifiers it holds". Hence, a namespace basically stores the names of the names of variables, objects, etc. To share a namespace means that the names of functions and variables are stored in the same space in Javascript. This means JS cannot differentiate between a variable and a function with the same name. Thus, they can overwrite each other and cause serious errors in the code. Hence, we should never have the same name for a variable and a function.

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'?
Answer: Constructs, in general, refer to building blocks. In JS, as functions behave as first class objects, we can pass a function to another function or return functions from other functions. Thus, similar to objects, a function inside a function is only accesible to that function. This makes our code more secure and prevents other functions or variables from interfering with that block of code. Thus, the program can run smoothly as small independent entities.

4. Can you explain the concept of a closure.
Answer:  Closure means a function, even after being by another function, can still be accessed from the parent function and vice-versa. This means one function can access all the variables inside the other function even after one has been called by the other. We can call the inner function with different values of arguments as many times we want but there will be no problem. (In the video, it is explained very well with the help of  an example so not elaborating any more.)

5. What is the difference between a function and a method?
Answer: Functions are methods are basically the same thing with the difference that methods are functions that  is associated with a object i.e., they are function sinside an object. In Javascript, it is difficult to differentiate between the two as there are no classes and most functions are in turn associted with an object.

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?
Answer: In JS, functions have a special parameter called "arguments" which holds all the arguments from invocation and can be traversed with the help of a loop as it contains a special length property (argument.length). Thus, each and every argument can be checked individually with the typeof  operator to check if it is of the desired type and also, the number of arguments can be checked with the length property.
example:
             function num(n){
             if((typeof n)!="number")
             {alert("Error: n is not a number!!!");
               break;
               }
             ...........
             }

7. Javascript functions have implicit access to something called thisthis 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.
Answer: The operator 'this' allows us to access variables inside a function and gives methos access to their objects. It is decided during function invocation what will this point to. Depending on the type of function invocation, this points to:
  1. Method form(thisObject.methodName(arguments))- this is set to thisObject i.e., the object containing the function.
  2. Function form(functionObject(arguments))-this is set to the global object..
  3. Constructor form(new functionObject(arguments))- a new object is created whenever new operator is used and this points to it.
8. Why doesn't Javascript have a cast operator?
Answer:  Typecasting refers to the conversion of one data type to another. It can be both implicit or explicit. In certain languages like C++, explicit type casting can be used to convert one data type into another explicitly i.e., by using the cast operator. However, in JS there is no explicit type casting i.e., the user does not need to specify when dealing with different data types. Hence, cast operator is not required.

9. What is reflection and why is it easy in Javascript (you may need to do research to answer this question)?
Answer: Reflection is when the code looks onto itself to discover its variables and functions. In Javascript, since basically everything is an object, reflection is easier as we can use a simple loop to check all variables and functions in an object without knowing their properties. Reflection is very well explained in this article.

 Well, finally catching up after two hectic weeks. I will be putting up the assignments soon; got a lot of catching up to do.

Friday, February 11, 2011

Week 2 : Assignments and Homework

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.
         The 'if... elseif' statements work fine when a few conditions are to be tested but become cumbersome when   many conditions are to tested. On the other hand, 'switch' statements ensures better readability and easier understanding of the code. Switch executes much faster than if..elseif(from wikipedia). Also, switch statement is far more efficient in cases where one value has to tested against a number of values. However, when different pairs of values are to be tested, if..elseif is a obviously better option.
       An example:  I am writing example 2.5 of Eloquent Javascript with the help of switch-
                            var ans=prompt("What is 2+2?","");
                            switch(prompt):
                                      {  case "4": alert("Bravo!!");
                                                      break;
                                        case "3":
                                        case "5": alert("Almost!!");
                                                      break;
                                        default:   alert("Stupid!!");
                                                      break;
                                        }
  
2. What is encapsulation, and what do functions encapsulate?
         Going by the OOP concept, encapsulation is simply packaging data and functions into a single unit. It is used to hide a object from outside of the object's definition. In Javascript, functions are used to encapsulate both variables and other functions. Whatever is defined within a function is not available outside it. However, blocks within curly brackets are merely chunks of code, they do not encapsulate.


3. What is a pure function? Is the function show() provided in Eloquent Javascript a pure function?
         In the book, pure function is defined as functions that always return the same value given the same arguments and never have side effects. That is, it produces no adverse effect on the program other than just taking some arguments and providing some values.
            The function show() is not a pure function as it has a side-effect, i.e., providing an output to the console. Thus, it produces an adverse effect other than returning a value.

4. What do we mean when we say a variable in a function is shadowing a top level variable?
          Suppose we create a variable inside and there is another variable of the same name outside that function. Now whenever that variable is referred inside the function, JS always checks its local environment( i.e., the function) and uses that value and only when nothing is found inside is the outside environment checked.  But when there is no variable of that name inside the function, it always shadows the top level variable.
          However, suppose we create 2 variables of same name- inside and outside the function. When inside the variable is used inside the function, the value inside the function is used. But when the variable is used outside the function, the value outside the function is used!!! Let me give an example:
           var myvar="I am outside the function.";
            function myFunc()
            {   var myvar="I am inside the function.";
                 print(myvar);
             }
           myFunc(); //function called
           print(myvar);
      Output:      
                   I am inside the function.
                   I am outside the function.
    
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?
   This is an interesting concept. Whenever a function is called, the control flows to the function i.e. execution of the function body starts. However, after the function body ends, the execution of the program resumes. So, there must be some place where the location within the function where the control broke-off can be "bookmarked"(i.e., the place where the function was called) so that normal execution can resume. This place where the "bookmark" is stored is called the stack.
   Recursive functions are functions which can call itself. This is possible with the help of stack. Every time a function is called, a new context is stored in the stack(i.e., a new function is placed over a stack of contexts). When a function returns, the context on top of the stack is taken off and resumed.
   If a recursive function doesn't have an end condition, it is supposed to run infinitely. Hence the stack grows bigger and bigger and when we reach the threshold of the stack, the "out of stack space" error is shown and further execution is prevented. Had this not been the case, there was a chance the system might end up crashing due to overloading.

6. Reflect about the difference between object inheritance and class inheritance
      Javascript supports prototypal inheritance. There are no classes in JS. Instead, we have objects which can be customized to create new objects. Whenever an object is created, it contains a secret link to another object. When access to the object fails, the link is used to refer to the linked object. In class inheritance, one class inherits from one or many classes and then, objects of that class has to be created to take advantage of the inherited properties. However, in JS, since there are no classes, objects directly inherit from other objects.
(For reference see, prototype based vs class based inheritance.)    
        Both types of inheritance are useful. Object inheritance is effective for code reuse while class inheritance can be used to create references of similar references.
      However, I do have a doubt(question to Parag) : In the video, Crockford says that an object can contain a link to only another object. Does this mean multiple inheritance is not supported in Javascript? Is there any way to make it work?

7. What is object augmentation, and how do we do it?
       This is great concept in Javascript. Unlike static object oriented languages, new members(functions or variables) can be added to objects without creating new classes. Only a simple assignment is required to add new members. This is undoubtedly a very powerful feature and helps us write smarter code.
example: say we have an object myHouse and want to add a new member 'rooms' which signify no. of    
              rooms. We simply use:
               myHouse[rooms]= 6

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?
     I found the answer to this question on www.crockford.com.
To add a method to any function prototype, we have to do this:
              function.prototype.method=function(name,func){ this.prototype[name]=func;
                                                                                         return this;};  // new function func is added to it by                              
                                                                                                                 using name
So, for a string I will use:        String.prototype.augment=newFunc(){.......//function body};
Now to use this new function newFunc() on a string variable say str, we can write:
                      str.newFunc();
          
9. What is garbage collection?
        Garbage collection refers to the deallocation of memory by collection of variables,functions,etc. that are no longer in use. It's an important part of any language and ensures that the memory is not blocked by unwanted variables. It seems JS uses the mark and sweep method of garbage collection.(courtesy google). Garbage variables, objects, etc. can also be delted using the 'delete' operator.
    For more on the mark and sweep method, refer this

10.What is the difference between an array and an object? 
        In Javascript, arrays are also objects(and inherits from objects). In objects, the keys can be names or strings. However, in arrays the data is numerically indexed. Arrays also have a property called 'length' which gives its size(i.e., 1 more than the last index). This helps in traversing an array with the help of a loop and perform various operations on the data. Also, in arrays we use [] as container as opposed to {}. We can also perform interesting fuctions on arrays like concat, join, splice, pop, push, sort.
        Arrays, like objects are secretly linked to array.prototype. However, arrays should not be used as prototypes as the object produced will contain the data but lose the array nature(i.e., length operator cannot be used). Like objects, arrays can be augmented by assigning methods to it.
example of array:
                        var arr=['one','two','three'];
                   Now, document.write(arr[0]) gives 'one'.
example of object:
                        var obj={first:'one',second:'two',third:'three'};
                   Now, document.write(obj.first) gives 'one'.
        Finally, to classify a variable as object or array, use '==='.
             if var.instance===array is true, it's an array.

Homework:


1. Exercises 3.1 from chapter 3 of Eloquent Javascript
Answer:    easy one:
                     function absolute(num)
                     {    if(num<0)
                                return -num;
                           else
                                 return num;
                        }

2. Exercises 3.2 from chapter 3 of Eloquent Javascript
Answer:     function greaterThan(x):
                   {      return test(y)
                           { return y>x;
                                     };
                                         }
                   var greaterthanTen=greaterThan(10);
                   show(greaterThan(8));

3. Shown below is some code which does something useful. The function 'iterateAndOperate' is the one which accomplishes something useful. The remaining code helps this function. Try to understand what the function accomplishes and solve the problems in part a, b, and c. The code can be done inside the console in Javascript, or in the web browser. Please see this comment, for hints on how you may do it inside a web page(remember, HTML has special codes for spaces and newlines).
  1. Use the function iterateAndOperate to draw an image which looks like this
  2. ++++@++++ +++@@@+++ ++@@@@@++ +++@@@+++ ++++@++++
  3. Use the function iterateAndOperate to draw a triangle which looks like this
  4. * *** ***** *** *
  5. In your code which invokes iterateAndOperate() without any parameters, as shown. An Exception will be thrown. Catch the Exception show an Alert to the user with a user friendly error message.
Answer: Now seriously, it would be cooler if instead of using an array, we could use a loop to print this out but since that is what is wanted, here goes:

<script type="text/javascript">           
 /A constant to hold the String "null". To be used in typeof checks
NULL_VAL = "null";
//A constant to hold the String "undefined". To be used in typeof checks
UNDEFINED_VAL = "undefined";

/*
 * This function checks if the specified parameter is null or undefined
 * @param something The specified parameter to check for a null or undefined value
 * @param name The name of the parameter. This will be used in the error message
 * If the value 'something' is found to be null or undefined, then this method
 * will throw an Error
 */
function checkNullOrUndefined(something, name) {
 if(UNDEFINED_VAL == typeof(something)) {
 throw new Error(name + " cannot be undefined");
  }
  if(NULL_VAL == typeof(something)) {
    throw new Error(name + " cannot be null");
  }
}


/*
 * This function accepts an array object and a function reference.
 * It iterates through the array and invokes the specified function
 * for every element of the array. In each invocation the current
 * array element is given to the function as a parameter.
 * @param arr The array
 * @param func The function to invoke for every element of the array
 * This method does not return any specific value.
 * This method throws an Error if 'arr' is null, undefined, or is not an array
 * This method throws an Error if 'func' is null, undefined, or is not a function
 */
function iterateAndOperate(arr, func) {
  checkNullOrUndefined(arr, "arr");
  checkNullOrUndefined(func, "func");
  // Verify that arr is an array
  if(!(arr instanceof Array)) {
    throw new Error("arr does not seem to be an array");
  }
  // Verify that arr is an array
  if("function" != typeof(func)) {
    throw new Error("func is not a function");
  }

  catch(err)
  {alert("Oops!! Seems like there is an error:"+err);
  }
  for(var i=0; i<arr.length; i++) {
    func(arr[i]);
  }
}
var arr1=["++++@++++","+++@@@+++","++@@@@@++","+++@@@+++","++++@++++",];
var  arr2=["*","***","*****","***","*"];
function print(var)
{ document.write(var); //to print the value
   document.write(<br/>);   //to add line break
}
iterateAndOperate(arr1, print); //for part a
iterateAndOperate(arr2, print); //for part b
iterateAndOperate();  ///for part c
</script>


.Note: It would be really helpful if someone could get clarify the multiple inheritance issue.
      

Monday, January 31, 2011

Homework for Week 1:

Ex 2.1 :((4 >= 6) || ("grass" != "green")) && !(((12 * 2) == 144) && true)
Is this true?
Solution: There are two expressions connected by &&.
The first part ((4>=6)||("grass"!="green")).
4>=6 is false.But grass!=green is true. So, this expression
is true.
The second part (((12*2)==144) && true).
(12*2)==144 is true. trues itself is always truthy.So, this
expression is true. (true && true)
So, true && true gives true.

Ex 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 * ....
Solution: Since, upto this point, only the while loop is explained, I am going to use this:
var result=1;
var counter=1;
while(counter<=10)
{ result=result*2;
counter=counter+1;
}
print(result);

Ex 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.
Solution: Here, again I will use the while loop:
var line=" ";
var counter=1;
while(counter<=10)
{ line=line+"#"; // concatenating the hashes
counter=counter+1;
print(line);
}

Ex 2.4: Rewrite the solutions of the previous two exercises to use for instead of while.
Solution: first problem-
var result=1;
var i=1;
for(i=1;i<=10;i++)
result=result*2;
print(result);
second problem:
var line=" ";
var i=1;
for(i=1;i<=10;i++)
{ line=line+"#";
print(line);
}

Ex 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.
Solution: var ans=prompt("what is 2+2?","think!!!");
if(ans=="4")
alert("Bravo!!");
else if((ans=="3")||(ans="5"))
alert("Almost!");
else
alert("Stupid!!");

Ex 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.
Solution:
var ans;
while(ans!=4)
{
var ans=prompt("what is 2+2?","think!!!");
if(ans=="4")
{alert("Bravo!!");
break;}
else if((ans=="3")||(ans="5"))
alert("Almost!");
else
alert("Stupid!!");
}
Note: In the above solution, the break statement is really unnecessary.

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

The && operator is also called the guard or the logical and operator. The && operator returns the first operand only if it is falsy(i.e, false,null,undefined,"",0) .Otherwise, it returns the second operand .
eg: var ans=prompt("Predict a number","");
var b=10;
var value= ((ans==10) && "Correct prediction!!!");
In the above example, the user is asked to predict a number. If the answer matches 10, then the output "Correct prediction!!!" is to be stored in a variable and displayed on the screen.

The || operator is also called the 'default' or the logical or operator. The || operator returns the second operand only if the first is falsy(i.e, false,null,undefined,"",0) .
eg: var ans=prompt("Predict a number","");
var b=10;
var value=((ans!=10) || "Wrong prediction.")
The above example is just the opposite of the previous example. Here if the user doesn't enter 10, wrong prediction is stored.



WEEK 1 - Track1

I watched the first video of the Douglas Crockford lecture series and also read the first three chapters of Eloquent Javascript. I personally feel one will benefit more if one watches the video after reading the chapters. I also consulted the JavaScript book by David Flannagan(the Rhinocerous book) which Crockford had recommended in the video.
Here are the answers to the questions :

1. The alliance of Netscape and Sun Microsystems did not use Java in the browser… Why do you think Java was not suitable to be embedded in a browser?
Java was simply too heavy a language and not suitable for browser scripting. In the 90's, most of the computers had dial-up connection and so, the load-and-go feature of Javascript was very useful for fast loading of web pages. Also, Java is a much more complex language than Javascript, on the lines of c++, with libraries, etc. So, the people at Netscape felt that they needed a simpler and hassle free language which could make browser scripting easier.

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?
The function parseInt(value, radix) converts the given value to a number according to the base or radix. Javascript converts the value to a number and stops when it encounters the first non-digit character in the given value according to the particular radix.Now suppose we enter the values as "08", "09" or "008" without a radix, JS might interpret the string as an octal integer. Since, only numbers 0-7 are allowed in octal system, it will terminate immediately as it encounters the value 8 or 9 thus giving the result in the three cases as 0. Hence, radix is always recommended.

3. What is a type, and why do you think types are useful in writing programs?
A type determines the form or category of value that a variable can contain. Types are extremely useful in classifying data. JS has the following types: numbers, strings, boolean, objects, undefined and null. Data types make it extremely convenient for us to perform various operations with the data at hand like comparing their values, performing addition, subtraction, etc. Data types prevent us from engaging in faulty operations on data like comparing a string and an integer. However, JS does have a few problems when we work on data of particular type( for example loss of precision in numbers.) Also, the + operator is used to both add numbers as well as concatenate strings. So, '2' + '4' gives 24.

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?
Javascript interprets all numbers as 64-bit floating point. 1 bit is used for the (+/-) sign in front of the numbers, 11 bits for the decimal point and remaining 52 bits for the number. For whole numbers that use 52 bits, this is not a problem. However, for pure decimal numbers, we end up losing precision when we perform arithmetic operations on them. For example, 0.1 + 0.2 gives 0.30000000000000004 as the answer as it uses up all 52 bits for providing the answer. Hence, while performing calculations which require precision like currency, we must always multiply the values by 100, and then divide the answer by 100.

5. Do you understand why the following operation produces the given result 115 * 4 – 4 + 88 / 2 = 500?
This is due to the fact that JS follows the standard rule of arithmetic operation: BODMAS( Brackets, orders or exponents, division, multiplication, addition, subtraction). So, for the given expression, first (115*4) and (88/2) is evaluated and the exp. becomes 460-4+44 which is equal to 500.

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 data type of the given value. Thus, typeof 4.5 will give "number"(without the quotes) as the output. typeof(typeof 4.5) is same as typeof("number"). As, "number" is a string, the output is the string "String" ( without the quotes).






Wednesday, January 19, 2011

Task 1:

The video gives us an insight into the following:-

Introduction:-
Javascript(JS) is one of the most widely used programming languages in the world used in various platforms. There are lots of misconceptions associated with it including JS being a subset of Java, it not being a complete programming language and that it makes browser scripting difficult. However, JS did suffer from a few problems like faulty implementation(though most of them have been corrected). Lastly, JS is a functional language.

History of Javascript:
In 1992, Oak developed at Sun was later turned into Java. Netscape later developed Livescript (later renamed Javascript) for browser scripting. Microsft developed their own implementation of JS called JScript. ECMA later decided the standard for JS.

Key Ideas in Javascript:
  • Load and go delivery-program delivered to execution site as source code
  • Loose Typing-any variable can receive any type of value!!!
  • Completely dynamic objects
  • Protoypal inheritance- objects inherit directly from other objects, no classes required
  • Lambda-use of functions as first class objects
  • Linkage through global variable- separate compilation units combined in a single space.however, this feature causes security problems,etc
Javascript Values:
Numbers, Strings, Boolean, Objects, null, etc are discussed. Some functions like Number, parseInt, math functions, string functions are touched upon. Identifiers and reserved words used in the language are also discussed. We also learn about the various types of operators like arithmetic, comparison, logical, bitwise, ternary.