Tuesday, 31 May 2011

Javascript week 2 questions for reflection


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?


Syntax: parseInt(string, radix)
parseInt() is used to convert string to number, but it stops at first non-digit character.
E.g.:      parseInt(“08”) will result in 0
              parseInt (“08”, 10) will result in 8
Radix is optional, it represents number (from 2 to 36) which is a numeral system (16 for hexadecimal, 8 for octal, 10 for decimal...) to be used.

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

      The type of values a program can work on is called as Data Types. String, Number, Boolean, Null are data types in JavaScript.
Data Types are useful as it manipulates data and produces some kind of results.

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


            There is only one Number type in JavaScript which is 64 bit floating point (double).

As by nature, floating point has maximum precision, they does not map well to common understanding of arithmetic.
E.g. 0.1 + 0.2 should ideally evaluate to 0.3
But 0.1 + 0.3 actually results to = 0.30000000000000004  

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


            Yes. This is because * and / has higher precedence over + and -.
115*4-4+88/2   = (115*4)-4 + (88/2)
                                =460-4+44
                                =456+44
                                =500            

5.     Will the following statement evaluate to true or false (("red" != "car") || (3 >= 9)) && !(((10 * 2) == 100) && true)


            It will evaluate to true.
((“red”! =”car”) || (3>=9)) &&! (((10*2) ==100) &&true)
(True || False) &&! ((20 ==100) && True)
True &&! (False &&true)
True &&! False
True && True
True

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


            typeof returns a string that identifies the data type of an expression.
typeof(4.5) returns a string which is “number”
so typeof(typeof(4.5)) returns string

No comments:

Post a Comment