Skip to main content

Ivan Teoh

Something personal yet public

Javascript: 101 Week 2 Track 1

On track 1 week 2, we are continuing understanding JavaScript through Douglas Crockford's video as below and chapter 3 on functions, from Eloquent Javascript.

Reflection

  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. According to the presentation, switch statement have it's own advantages. The switch value does not need to be a number. It can be a string. The case values can be expressions too.

    166-reflection1.js (Source)

    switch (expression) {
        case 'a':
        case 'b':
        case 'c':
            alphabet();
            break;
        default:
            nonAlphabet();
    }
    
  2. What is encapsulation, and what do functions encapsulate? In simple words, encapsulation means information hiding. The functions encapsulate local variables and functions that are created in side the functions.

  3. What is a pure function? Is the function show() provided in Eloquent Javascript a pure function? According to the book, the defining properties of pure functions are that they always return the same value when given the same arguments, and never have side effects. They take some arguments, return a value based on these arguments, and do not monkey around with anything else. The function show() is not a pure function as it is not self-sufficient.

  4. What do we mean when we say a variable in a function is shadowing a top level variable? It means the local function variable have a same name with a top level variable. When looking up a variable inside a function, the local environment is checked first, and only if the variable does not exist there is it looked up in the top-level environment. This makes it possible for variables inside a function to 'shadow' top-level variables that have the same name.

  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? According to the book, when a recursive function is called, control is given to the body of that function. When that body returns, the code that called the function is resumed. While the body is running, the computer must remember the context from which the function was called, so that it knows where to continue afterwards. The place where this context is stored is called the stack. This stack requires space in the computer's memory to be stored. When the stack grows too big, the computer will give up with a message like "out of stack space" or "too much recursion".

  6. Reflect about the difference between object inheritance and class inheritance According to the presentation, some languages have classes, methods, constructors, and modules. JavaScript's functions do the works of all of those. Instead of class inheritance, JavaScript has object inheritance. In other words for object inheritance is prototype inheritance. It accomplishes the same things, but differently. It offers greater expressive power. Instead of organizing objects into rigid classes, new objects can be made that are similar to existing objects, and then customized. Object customization is a lot less work than making a class, and less overhead, too. One of the keys is the object(o) function. The other key is function. The object(o) function makes a new empty object with a link to object to. Refer to the Douglas Crockford - inheritance for more classical inheritance in JavaScript.

  7. What is object augmentation, and how do we do it? According to the Douglas Crockford - inheritance, in the static object-oriented languages, if you want an object which is slightly different than another object, you need to define a new class. In JavaScript, you can add methods to individual objects without the need for additional classes. This has enormous power because you can write far fewer classes and the classes you do write can be much simpler. New members can be added to any object by simple assignment, for example, myobject[name] = value;

  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? Using linkage.

  9. What is garbage collection? According to JavaScript: The Definitive Guide, 4th Edition, JavaScript uses garbage collection to reclaim the memory occupied by strings, objects, arrays, and functions that are no longer in use. This frees you, the programmer, from having to explicitly deallocate memory yourself and is an important part of what makes JavaScript programming easier than, say, C programming. A key feature of garbage collection is that the garbage collector must be able to determine when it is safe to reclaim memory. Obviously, it must never reclaim values that are still in use and should collect only values that are no longer reachable; that is, values that cannot be referred to through any of the variables, object properties, or array elements in the program.

  10. What is the difference between an array and an object? According to the presentation, array inherits from object. The indexes are converted to strings and used as names for retrieving values. Arrays, unlike objects, have a special length member. Arrays allows use of the traditional for statement. Only use for..in for objects and not arrays. The dot notation also should only use for objects and not arrays. Use objects when the names are arbitrary strings. On the other hands, use arrays when the names are sequential integers. We can't use arrays as prototypes as the objects produced this way does not have array nature. It will inherit the array's values and methods, but not its length. We can augment an individual array by assigning a method to it. This works as arrays are objects. We also can augment all arrays by assigning the methods to Array.prototype.

Homework

  1. Exercises 3.1 from chapter 3 of Eloquent Javascript: Write a function called absolute, which returns the absolute value of the number it is given as its argument. The absolute value of a negative number is the positive version of that same number, and the absolute value of a positive number (or zero) is that number itself.

    166-homework1.js (Source)

    function absolute(number) {
        if (number < 0)
            return -number;
        return number;
    }
    
  2. Exercises 3.2 from chapter 3 of Eloquent Javascript: Write a function greaterThan, which takes one argument, a number, and returns a function that represents a test. When this returned function is called with a single number as argument, it returns a boolean: true if the given number is greater than the number that was used to create the test function, and false otherwise.

    166-homework2.js (Source)

    function greaterThan(number1) {
        function test(number2) {
            return number2 > number1;
        }
        return test;
    }
    
    var greaterThanTwenty = greaterThan(20);
    alert(greaterThanTwenty(52));
    alert(greaterThanTwenty(10));
    
  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).

    166-homework3.js (Source)

    //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");
      }
      for(var i=0; i<arr.length; i++) {
        func(arr[i]);
      }
    }
    
    1. Use the function iterateAndOperate to draw an image which looks like this

      166-homework31.txt (Source)

      ++++@++++
      +++@@@+++
      ++@@@@@++
      +++@@@+++
      ++++@++++
      

      Code:

      166-homework31.html (Source)

      <!DOCTYPE HTML>
      <html lang="en">
      <head>
          <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
          <title>JavaScript 101</title>
          <script type="text/javascript">
              function load()
              {
                  // 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");
                    }
                    for(var i = 0; i<arr.length; i++) {
                      func(arr[i]);
                    }
                  }
      
                  function draw(symbol) {
                      function plusDraw(sign) {
                          for (var j = 0; j < sign; j++) {
                              document.write("+");
                          }
                      }
                      var total = 9;
                      var plus = (total - symbol)/2;
                      plusDraw(plus);
                      for (var j = 0; j < symbol; j++) {
                          document.write("@");
                      }
                      plusDraw(plus);
                      document.write("<br />");
                  }
                  iterateAndOperate([1, 3, 5, 3, 1], draw);
              }
          </script>
      </head>
      <body onload="load()">
      </body>
      </html>
      
    2. Use the function iterateAndOperate to draw a triangle which looks like this

      166-homework32.txt (Source)

      *
      ***
      *****
      ***
      *
      

      Code:

      166-homework32.html (Source)

      <!DOCTYPE HTML>
      <html lang="en">
      <head>
          <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
          <title>JavaScript 101</title>
          <script type="text/javascript">
              function load()
              {
                  // 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");
                    }
                    for(var i = 0; i < arr.length; i++) {
                      func(arr[i]);
                    }
                  }
      
                  function draw(symbol) {
                      for (var j = 0; j < symbol; j++) {
                          document.write("*");
                      }
                      document.write("<br />");
                  }
      
                  iterateAndOperate([1, 3, 5, 3, 1], draw);
              }
          </script>
      </head>
      <body onload="load()">
      </body>
      </html>
      
    3. 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.

      166-homework33.html (Source)

      <!DOCTYPE HTML>
      <html lang="en">
      <head>
          <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
          <title>JavaScript 101</title>
          <script type="text/javascript">
              function load()
              {
                  // 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) {
                      try {
                          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");
                          }
                          for(var i = 0; i < arr.length; i++) {
                              func(arr[i]);
                          }
                      }
                      catch(e){
                       alert('An error has occurred: '+e.message)
                      }
                  }
                  iterateAndOperate();
              }
          </script>
      </head>
      <body onload="load()">
      </body>
      </html>
      

Comments

Comments powered by Disqus