Tuesday, February 15, 2011

JavaScript 101 -- week 2 -- track 1 (for now)

I apologize for this being so ridiculously late, but i have been really busy lately. Through doing this assignment, I have realized that it might be best for me to change to track 1... I dont feel like i have enough background in coding to fully grasp every concept yet. For this reason, the less accelerated track will benefit me more. I hope that Track 2 is well organized (some recent posts would suggest otherwise).

-My track 3 homework will be up asap, and hopefully I can catch up by the deadline for week 4
  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.

Answer: if/elseif strings will run through the entire sequence of statements, and if there are a lot of options, it could add a lot of time to the running of your program. Switch statements have different “cases” and the thread jumps right to the appropriate choice and then gets out of the loop with a “break”. For an instance with many cases, switch is the best choice.

EX:

var gameName = monopoly

switch (gameName) {

case “scrabble”:

alert (“scrabble is a word game”);

break;

case “chess”:

alert (“chess is a strategy game”);

break;

case “monopoly”:

alert (“monopoly is a business game”);

break;

default:

alert (“unknown game”);

break;

}


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

Answer: encapsulation is when Information is privately seen by a function (information that can not be changed from outside the function)

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

Answer: a pure function has one input and one output and is one that does not change anything outside of the function or, rather, has no side effects. Show() has side effects -- it writes text to the screen and requires an output text box to function properly

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

Answer: Variables declared in functions are unique to that function. This means that functions can reuse the name of a variable from the program without effecting the original variable’s value. This is called shadowing.

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

Answer: there is a limited amount of memory. each time a function is called, it is placed in the memory. If another is called, it is also added to the memory. In a recursive function, memory is continually taken up until the function loop is broken. This is called a “stack” -- instances of the function are being stacked up in the memory.

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

Answer: Inheritance is where an object inherits the qualities of something else. Object inheritance occurs when a new object is created and set equal to an existing object. That object then has all of the same characteristics as the original object. Class inheritance is different, in that when an object is set equal to a class, the object only refers to the characteristics of the class. This means that if the class changes, the object reference changes as well.

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

Answer: an object holds sets of values -- a string, and a non type-specific variable. new sets can be added at any time using a simple assignment statement. If someone has an object “car”

with sets { “color”:”blue” , “year”:1997 } someone could add a set called “model” by saying car.model = “focus”;

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

Answer: add the new method to String.prototype

  1. What is garbage collection?

Answer: garbage collection removes all unnecessary data from the memory. For example, once a for statement is finished running, it no longer needs the counter initialized from within that function. this value is removed from memory, helping to prevent memory overload and maintain efficiency

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

Answer: objects are unordered pairs of values -- a string to name the pair, and a non-type-specific variable. An array has an order and a length. Instead of having a string name, it is organized by its number, or space in the array. if you want to add something to an object, it does not effect the other pairs. however, if you want to add something to an array, you will need to slide the other pairs over to make room, or simply add it to the end of the array.

Homework:
Ex. 3.1
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.

ANSWER:

function absVal (a) {
if (!a) return ("you did not enter an interger");
else if (a< 0) return (-1 * a);
else return a;
}


alert(absVal( (prompt("type an interger", ""))*1) );


Ex. 3.2
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.

ANSWER:

function isGreaterThan(x) {
return function(y) {
return y > x;
};
}

var firstChoice = isGreaterThan(prompt("pick a number",""));
alert(firstChoice(prompt("is this number is greater than the first?","")));than the first?","")));

Monday, January 31, 2011

Homework - week 1 (track 1)

JavaScript 101: Homework -- Week 1

  1. The alliance of Netscape and Sun Microsystems did not use Java in the browser, because it was not suitable for that purpose. Why do you think Java was not suitable to be embedded in a browser?


Answer: Java is run as an executable, while JavaScript is run through a browser as text. This means that javaScript is easily added to the body of HTML -- which is also read via the browser as text.

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


Answer: The Radix argument tells the parsInt function which base to use for the returned variable. This is important because text might mean one thing, but is interpreted by the computer as another. for example, if there is a string that is meant to be hexidecimal, the parsInt funtion will only return the first numbers before any letters appear. If the radix is set as 16, this string will then properly return the value.

  1. What is a type, and why do you think types are useful in writing programs?


Answer: Any value has a type. For example, var ex = 7; is type “Number” while var ex = “7” is type “String” -- this is an important distinction because one program may require a number value -- if the type is tested, one can insure that this value is a number and not another incompattible type, like a boolean.

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


Answer: JavaScript only has 64 bits of precision. this means that when a number is anything but a whole positive integer, extra bits are used to indicate things like a negative integer and where the decimal place falls within the number. This means that only 52 bits are left for the digits in a number.

  1. Do you understand why the following operation produces the given result 115 * 4 - 4 + 88 / 2 = 500


Answer: JavaScript uses order of operations to determine what should be calculated first. In this case, multiplication and division are calculated first. The language is essentially adding in parenthesise into the equation. If parenthesise were added, the equation looks more like this:

(115 * 4) - 4 + (88 / 2) = 500

this simplifies to:

460 - 4 + 44 = 500

  1. What does typeof 4.5 do, and why does typeof (typeof 4.5) return "string" ?


Answer: the typeof is a function that returns a string. this string gives you the type of a particular value. This means that when typeof takes a number value, a string is returned that says “number.” Similarly, if a string value is given, typeof returns the string “string.” Because typeof always returns a string value, “typeof (typeof x)” will always return the string value “string.”


Ex. 2.1:

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

Is this true?


Answer:
= (false || True) && !(false && true)
= (true) && !(false)
= true && true

= 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).

Answer:
//Code:
var base = 2, power = 10, answer = 1, count = 0;

while (count <>

{

answer *= base;
count += 1;

}


alert (answer);

//Output: 2024

/* alternative:
var base = 2, power = 10;

alert(math.pow(base,power));

//This uses the Math object, with function “pow”
*/

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

var count = 0; numLines = 10;
line = ""; output = "";

while (count <>
{
line += "#";
document.write(line);
count += 1;
}
/*output:
#
##
###
####
#####
######
#######
########
#########
##########
*/

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

Answer: a)

var base = 2, power = 10, answer = 1;

for (var x = 0; X <>

answer *= base;

alert (answer);

---------------

b)

var numLines = 10;

line = ""; output = "";


for (var x = 0; x <>

{

line += "#";
document.write(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.

Answer:
answer = prompt ("what is 2+2","????");
if (answer == "4")
alert ("yay! you aren't dumb!");

else if (answer == "3" || answer == "5")
alert ("almost... you're kinda dumb though...");

else
alert ("you are OFFICIALLY dumb!");

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.

Answer:
correctAns = false;
var answer;

while (!correctAns)
{
answer = prompt ("what is 2+2","????");
if (answer == "4")
{
correctAns = true;
alert ("yay! you aren't dumb!");
}

else if (answer == "3" || answer == "5")
alert ("almost... you're kinda dumb though...");

else
alert ("you are OFFICIALLY dumb!");

}


**Create an example that shows a valid use of the 'guard' and 'default' operators in Javascript.

Answer:

//default = ||

alert ((prompt("pick a number") || "you did not pick a number"));
/* if the person picks a number, it is displayed. If they dont, the message “you did not pick a number” is displayed */

//guard = &&

a = prompt("guess the right number");
alert (a && 5);
/* you are prompted to “guess the right number.” If your number is wrong, it will display the correct number. If its right, it will display the correct number.