Wednesday, February 9, 2011

Week 2 assignment - track 1

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.

Switch statement is more readable and more versatile than multiple if...else if statements.

var Month = 13;

switch(Month)
{
    case 1:
            alert('January');
            break;
    case 2:
            alert('February');
            break;
    case 3:
            alert('March');
            break;
    case 4:
            alert('April');
            break;
    case 5:
            alert('May');
            break;
    case 6:
            alert('June');
            break;
    case 7:
            alert('July');
            break;
    case 8:
            alert('August');
            break;
    case 9:
            alert('September');
            break;
    case 10:
            alert('October');
            break;
    case 11:
            alert('November');
            break;
    case 12:
            alert('December');
            break;
   default: alert('not a month of the year');
}

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

Wikipedia defines encapsulation in object-oriented programming as:
- A language mechanism for restricting access to some of the object's components.
- A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data.
JavaScript functions encapsulate variables. The variables declared inside a function are not visible outside that function.

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

Pure functions always return the same value when given the same arguments and never have side effects.
The function show() from Eloquent Javascript is not a pure function because it has the as side effect the text display on an output canal.

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

When we have a global variable and a variable declared inside of a function, both with the same name, the call of the variable will use the value set in that function.

var A=2;
function test()
{
    var A=3;
    print("A=" + A);
}

test();

// A=3 is printed

var A=2;
function test()
{
    var A;
    print("A=" + A);
}

test();

// A=undefined is printed


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?

Every time a function is called the context is stored on the stack. When function returns the context on top of the stack is taken off stack and resumed. A recursive function without an end condition will call itself endlessly running out of stack space very fast.

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

In object inheritance objects are derived from existing objects and then customized dynamically. All objects are  ultimately derived from Object.prototype. It's much simpler than class inheritance that requires class definitions and object instantiations. Object inheritance provides simple inheritance vs. multiple inheritance provided in other languages with class inheritance.

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

By object augmentation new members can be added to any object at any time by simple assignment.

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 have to augment String.prototype since all Strings derive from String.prototype.

9. What is garbage collection?

Garbage collection it's a mechanism based on mark-and-sweep principle. Javascript interpreter detects when an object will be never used again by the program and reclaims the memory, so the programmer doesn't have to keep track of memory allocation/deallocation.

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

Arrays have a length member unlike objects.

Homework

1. Exercises 3.1 from chapter 3 of Eloquent Javascript

function absolute(num)
{
    if (num >= 0)
        return num;
    else
        return -num;
}

var num=-10;
print(absolute(num));

And cheeting...

function absolute(num)
{
    return Math.abs(num);
}

var num = 11;
print(absolute(num));

2. Exercises 3.2 from chapter 3 of Eloquent Javascript

function greaterThan(num) {
return function(compared) {
return compared > num;
}};

var greaterThanNum = greaterThan(10);
show(greaterThanNum(15));

3.

3.1.

A dummy use of iterateAndOperate:

function fTest(a)
{
  document.write(a);
}

var arr = new Array();

var s = '++++@++++';
arr = s.split('');
iterateAndOperate(arr, fTest);
fTest('<br>');

var s = '+++@@@+++';
arr = s.split('');
iterateAndOperate(arr, fTest);
fTest('<br>');

var s = '++@@@@@++';
arr = s.split('');
iterateAndOperate(arr, fTest);
fTest('<br>');

var s = '+++@@@+++';
arr = s.split('');
iterateAndOperate(arr, fTest);
fTest('<br>');

var s = '++++@++++';
arr = s.split('');
iterateAndOperate(arr, fTest);

A more inteligent use:

function pattern1(n)
{
  var line = '';
  for(i=0; i<(9-n)/2; i++){
    line += '+';
  }
  for(i=0; i<n; i++){
    line += '@';
  }
  for(i=0; i<(9-n)/2; i++){
    line += '+';
  } 
  document.write(line);
  document.write('<br>');
}

var arr = [1,3,5,3,1];
iterateAndOperate(arr, pattern1);

3.2

function pattern2(n)
{
  var line = '';
  for(i=0; i<n; i++){
    line += '*';
  }
  document.write(line);
  document.write('<br>');
}

var arr = [1,3,5,3,1];
iterateAndOperate(arr, pattern2);

3.3

try
{
  iterateAndOperate();
}
catch(error)
{
  alert("Please provide parameters. " + error);
}

Saturday, January 15, 2011

Notes about JavaScript Basics - 1 video

Douglas Crockford ‘s video about Javascript basics -1 shows the background and evolution of  what  Javascript is today: a very popular,  platform independent, object based, client and server side, complete programming language, which uses a C type of  syntax, from the functional languages family, the result of  Sun and Netscape collaboration.

Javascript distinguishes itself from the other languages by the following key concepts:

1.    Load and go delivery: programs are delivered to the execution site as text.
2.    Loose typing: even it’s against the today’s “strong typing” main stream it improves the processing
power and makes the coding process easier.
3.    Objects as general containers: it unifies objects and hashtables creating very dynamic objects.
4.    Prototypal inheritance: objects inherit directed from other objects, there are no classes.
5.    Lambda: use of classes as first class objects.
6.    Linkage through global variable:  defines a global namespace that raises security and reliability
problems.

Javascript has a small number of values:

1.    Number:  there is only one number type, represented as 64 bit floating point and it does not map well

the common understanding of arithmetic.
NaN: Not a Number – a special value, the result of undefined or erroneous operations.
Number function: Number(value) – similar to + prefix operator, converts a value to a number.
parseInt function: parseInt(value, radix) .
Math object: copied Java’s Math class.
2.    String: represented by 16 bit charactes, using UCS-2 encoding, immutable.
String function: String(value) – converts value to a string.
Strings are objects and have methods (like length).
3.    Boolean: true or false.
Boolean function: Boolean(value) – deals with truthy and falsy concepts.
4.    null: a value that isn’t anything.
5.    undefined: default value for variables and parameters, the value of missing members in objects.
6.    Objects: new Object() produces an empty container of name/value pairs

The video describes also the characteristics of:
-    Identifiers
-    Reserved words
-    Comments
-    Operators: they are similar to those in C languages with a few nuances

My JavaScript solution for the task 2 stated in the prerequisite is:

<html>
<head>
<script type="text/javascript">
function sum(a,b)
{
return a+b;
}function message()
{
alert("2+2=" + sum(2,2));
}
</script>
</head>
<body onload="message()">
</body>
</html>