Monday 13 June 2011

Javascript week 5 questions for reflection


1.     What are the roles of 'name' and 'id' attributes in HTML tags? What is an appropriate use of both?


Name and Id attribute is used to get the required element from the document.
< input type="text" name="email" id=”txtEmail”/>
Id attribute accepts unique values, which can be used to identify the element from the document by using getElementById method
var vObjEmail = document.getElementById(“txtEmail”);
Name specifies the name of an element. Document.getElementsByName can be used to get elements with the specified names.
By using getElementById & getElementsByName, we can avoid traversing across intermediate nodes and hard coding paths.

2.     Which pointers does each node in the DOM tree typically have?


Each element on the HTML page is considered as node in the DOM tree.
Each node has parentNode and childNode property. Using parentNode parent object of node is obtained and using childNode, array of child nodes is obtained.

3.     Given a node object from a DOM tree, how do we determine if it is a text node or a regular node?


nodeName property gives information about the node’s type. By checking the nodeName property of a node, we can determine if it’s a text node or regular node.
If the nodeName property is “#text”,it is text node.

4.     Why is it better to use either trickling or bubbling of events? Why not just give the event to the node on which it was invoked?


Suppose there is element inside an element and both have click events. And the click event of element 2 is fired first then click event of element1 is called event bubbling. And reverse is click event of element 1 is fired then click event of element 2 is called event capturing.
We can decide whether to register event handler in capturing or bubbling phase. This is done through addEventListener() method
element1.addEventListener('click',doSomething2,true)
element2.addEventListener('click',doSomething,false)
If the last argument is true, event is set to capturing phase, if false it is set to bubbling phase.

5.     Can you think of one situation where you would want to prevent the browser from submitting a form after a user has clicked on the 'submit' button? How would you achieve this?


Suppose there are some validations that must be satisfied before submitting data to server. In that case, we can validate data using JavaScript on button click, if all validation is done then save data otherwise return from the function.
This is done by using “return false” or event.preventDefault(); which will stop further propagation of events.

Tuesday 7 June 2011

Javascript week 4 questions for reflection

1.      In JavaScript, functions are first class objects. What does it mean to be a first class object?

In JavaScript, functions can be passed, returned and stored just like any other value.
First class object is an entity which is constructed dynamically, passed as parameter, returned from method and assigned to variable.
E.g. function attachEventToBtn () {
btnOk.click = function () {
                alert (‘Click’);
}
}
                E.g. var vResults = validateFileName ();

2.      Functions and variables share the same namespace. What does this mean and what important implication does this have?

Function and variables share the same namespace means, function and variables can have same name.
E.g. var foo = function foo() {
  alert('Yes');
};
foo();
alert(foo); 

3.      Douglas Crockford equates JavaScript functions with Lambdas, and also mentions that they are a secure construct. Can you do some research and reflect on what he means by 'secure construct'?

As Douglas Crockford mention JavaScript functions are source to enormous expressive power and it’s secure. Secure in the sense that functions have well defined scopes, which keeps code enchant. 

4.      Can you explain the concept of a closure?

Closure means even after parent function is returned, inner function defined with the parent function can have access to parent function variables.
E.g. function attachEventToBtn () {
btnOk.style.display = ‘none’;
btnOk.parentNode.innerHTML = ‘<input type="button" id=”btnSave” value="Save"/>’ + btnOk.parentNode.innerHTML;
btnSave.click = function () {
                alert (‘Click’);
btnOk.click();
}
}

5.      What is the difference between a function and a method?

Function can be referred as variable, which can be stored & return value and used as parameter.
As function is used like value, it can be stored in Objects. And a function in objects is called as Method.

6.      In JavaScript there is no implicit type checking of arguments passed to functions. This could lead to bugs if programmers are not careful about what they pass to functions. If you create a function, how would you protect it from well-meaning but careless programmers?

As JavaScript is loosely typed language, we cannot declare argument type in function declaration. If we pass wrong type, it will break the code. In order to protect the code we can use the typeof () operator to check the type of argument passed to the function.

7.      JavaScript functions have implicit access to something called this. this points to different things depending on how the function was created. Can you explain why we need this, and what it represents in different type of functions?

In most of the languages this refers to the current object initiated by class. In JavaScript this refers to the object owned by the method, but it depends on how it is called.
function setStyle(){
this.style.color='Gray';
}
In above case setStyle will refer to window
element.onclick=setStyle()
In above case it will refer the element

Tuesday 31 May 2011

Javascript week 3 questions for reflection

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

Encapsulation means variables defined in a scope are not visible outside the scope.
Function scopes can create encapsulate, as variables declared in functions are not visible outside of the function. You can use anonymous function to wrap your application.

2.      What is a pure function?

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.

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

Recursive function calls same function until the end condition is met. When a function is called, memory space is allocated for the local variables within the function and they are pushed in the stack. When function exit, the space on the stack is removed.
If recursive function does not have end condition, stack will go on adding local variable and we will reach out of space on stack.

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

Class Inheritance:
·         There are classes and instances. Both are two different entities
·         Classes are defined and initiated with constructor method.
·         Construct an object hierarchy by using class definitions to define subclasses of existing classes.
·         Inherit properties by following the class chain.
·         Class definition specifies all properties of all instances of a class. No way to add properties dynamically at runtime.

Object Inheritance:
·         Every object is instance.
·         Set of objects are defined and created with constructor functions.
·         Construct an object hierarchy by assigning an object as the prototype associated with a constructor function.
·         Inherit properties by following the prototype chain.
·         Constructor function or prototype specifies an initial set of properties. Can add or remove properties dynamically to individual objects or to the entire set of objects. 

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

Object augmentation is a process, in which new members can be added to any object by simple assignment. There is no need to define new class, as there are no classes in JavaScript.
Suppose there is an object  :
 var vObj = {
Id : 1,
 State: “Maharashtra”
} ;
                I can add another object or property to this object at same time or later on:
var vObj = {
Id : 1,
 State: “Maharashtra”,
City : {  CityId : 12,
Title: “Pune”}
} ;


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

Friday 20 May 2011

Introduction To Javascript Week 1

Here's a simple example of Javascript to show alert.

<html>
<body>

<h1>My First Web Page</h1>

<script type="text/javascript">
alert("Hello World!")
</script>

</body>
</html>