Reading
The Assignment
Introduction
This assignment is an exercise in working with objects, functions, conditionals, and loops. As in the previous two assignments, you are to prepare a script file that demonstrates features of JavaScript and answers some questions.
Replace all links to scripts in your index.xhtml page with a new link to a single script file named scripts/assignment_04.js. Create that file, and edit statements into it as you work through the assignment steps.
Assignment Steps
-
Create a function that receives one parameter and displays the parameter’s type.
Name the function foo(). You may do it either of two ways
foo = function(param) { console.log("foo: param is of type '" + typeof param + "'."); };orfunction foo(param) { console.log("foo: param is of type '" + typeof param + "'."); }There is a difference between the two: the first technique defines the function when the assignment to foo takes place. The second one defines the function as soon as the script is loaded by the browser. If you wanted to you, you could put the second type of function definition at the end of the script file, and still use it at the beginning.
For this assignment, you need to keep re-defining foo(), so except for the first time you define the function, you will have to use the assignment statement form. For the first definition you could use either form.
When the function is defined, call it five times, passing it the following values:
- { }
- [ ]
- 123
- "1"
- foo
Explain each of the five lines of output.
-
Redefine foo() so it recognizes arrays and objects.
The goal is to get one of the following messages to print out, depending on what is passed as an argument to foo() when it is called.
- foo: param is an array
- foo: param is an object
- foo: param is neither an array nor an object
For example, for the five calls in the first step, the messages should be:
foo: param is an object foo: param is an array foo: param is neither an array nor an object foo: param is neither an array nor an object foo: param is neither an array nor an objectFor this assignment, you may simply make the assumption that if an object has a length property, it is an array. You should know by now that it is possible to add any property to any object, so this test is not foolproof. But we will not try to make fools of ourselves!
To do this step, you will have to use if statements (textbook pages 36-43). I’m giving you the hard part, telling if the parameter is an array. You have to add the else and else if parts to make it a three-way decision.
foo = function(param) { if ( (typeof param === "object") && (typeof param.length === "number") ) { console.log("foo: param is an array"); } else { console.log("foo: param is not an array"); } } -
Redefine foo() so it sums numerical elements if the parameter is an array.
For both parts of this step, use for loops. There is an example of using a for loop to double all the elements in an array on page 47 of the textbook. Here is the code to sum all the elements in an array:
var numbers = [ 1, 2, 3, 4, 5, -16 ]; var sum = 0; for (var i = 0; i < numbers.length; i++) { sum = sum + numbers[i]; } console.log("The sum is " + sum + ".");Note that it is very important to initialize the variable sum before looping through the numbers.
The statement inside the loop could have been written using the shorthand, sum += numbers[i]; if you want to save a little typing.
But for this assignment, you have to test each element of the array to be sure it is a number:
if (typeof param[i] === "number") sum += param[i];The body of an if statement does not have to be inside curly braces if there is only one statement. In the above example, the braces are omitted and the single statement is moved to the same line as the if test. Never omit the braces when putting a single statement body on a separate line: it almost always leads to errors later on.
You can use the following lines of code to test your function:
console.log("foo([100, 20, 3, 'hello']);"); foo([100, 20, 3, 'hello']); console.log("foo({a:100, b:'20', c:20, d:3});"); foo({a:100, b:'20', c:20, d:3}); console.log("foo(123);"); foo(123); console.log("foo('1');"); foo('1'); console.log("foo(foo);"); foo(foo); -
Add code to foo() so it sums the numeric properties of objects.
Use a different kind of for loop to do this. JavaScript has a special type of for loop for iterating over the properties of an object, but it is not covered in the textbook. Here is an example of it in action:
var obj = { a:3, b:5, c:"hello", a_long_property_name:7 }; for (var property_name in object) { console.log("obj." + property_name + " has the value " + obj[property_name]); }I’ll explain this below, but it’s good enough if you can see the pattern in the example and adapt it to the assignment. After you have updated the function, use the same set of function calls to test it. You should see the sum for the numeric property values as well as the sum of the numeric array elements.
Gory Details
This type of for loop assigns the name of each property in an object, as a string, to the loop variable (property_name in the example) on each iteration. You may recall that we could use strings and negative numbers as subscripts for arrays, but that those elements don’t count in the length of the array. You may also recall that arrays are actually objects. Putting it all together, if you use a non-negative integer subscript, you can assign values to the “array part” of an array, but if you use negative integers (or non-integers, like 1.2) or stings as a subscript, you are using the “object part” of an array with the added twist that the subscript values do not have to be valid property names; if they are not strings, they get converted to strings. And you can use variables holding the string representations of these property names as subscripts!
This is a rather obscure topic at this point. But being able to iterate over the properties of an object can be a very useful debugging technique that you can use even if you don’t understand exactly how it works.
Here is some sample code and the output it generates. (Math is an object built into JavaScript that has a property named PI that holds the value of the mathematical constant, π.)
var a = [ 1, 2, 'hello']; a[-1] = 123; a[Math.PI] = "I like apple"; a['something'] = 321; for (p in a) { console.log("p is a " + typeof p + " and its value is '" + p + "'. a[p] is " + a[p]); } console.log("a.something is " + a.something); console.log("a['something'] is " + a['something']); console.log("The length of array a is " + a.length); --------------------------------------------------------------------------------------- p is a string and its value is '0'. a[p] is 1 p is a string and its value is '1'. a[p] is 2 p is a string and its value is '2'. a[p] is hello p is a string and its value is '-1'. a[p] is 123 p is a string and its value is '3.141592653589793'. a[p] is I like apple p is a string and its value is 'something'. a[p] is 321 a.something is 321 a['something'] is 321 The length of array a is 3 -
Check your program’s output.
It should look like this, but without the step number messages:
Step 1
foo([ ]); foo: param is of type 'object'. foo({ }); foo: param is of type 'object'. foo(123); foo: param is of type 'number'. foo('1'); foo: param is of type 'string'. foo(foo); foo: param is of type 'function'.Step 2
foo([ ]); foo: param is an array foo({ }); foo: param is an object foo(123); foo: param is neither an array nor an object foo('1'); foo: param is neither an array nor an object foo(foo); foo: param is neither an array nor an objectSteps 3 and 4
foo([100, 20, 3, 'hello']); foo: param is an array foo: the sum of the numeric elements in the array is: 123 foo({a:100, b:'20', c:20, d:3}); foo: param is an object foo: param.a is of type 'number' foo: param.b is of type 'string' foo: param.c is of type 'number' foo: param.d is of type 'number' foo: The sum of the numeric properties is 123 foo(123); foo: param is neither an array nor an object foo('1'); foo: param is neither an array nor an object foo(foo); foo: param is neither an array nor an object
Submit
When you have tested your code and determined the answers to the questions, type your answers into the body (not an attachment) of an email message, and send it to me. I’ll copy your entire web site to my computer (babbage) and check out your code and will check your email to be sure you answered the questions correctly.
Send your email message to me at: vickeryatbabbage.cs.qc.cuny.edu by midnight of the due date.
The Subject line of your email message must be: “CS-90.3 Assignment 4.”
Don’t forget to put your name in your email message!