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.