A. The first statement puts the variable in the scope of whatever function it was defined. The second statement places the variable in global scope. Global scope can potentially cause collision with other variables with the same name. Therefore, the keyword var must be used when defining variables, and an anonymous function should be used as a closure if needed, encapsulating multiple functions which can share access to the same set of variables. That makes sure the variables stay sandboxed, accessible only by those functions which need them.

Q. What is the difference between the following 2 statements?

!!(obj1 && obj2);
(obj1 && obj2);

A. The first statement returns a “real” boolean value, because you first negate what is inside the parenthesis, but then immediately negate it again. So, this is like saying something is “not not” truth-a, making it true. The second example simply checks for the existence of the obj1 and obj2, but might not necessarily return a “real” boolean value, instead returning something that is either truth-a or false-a. This can be problematic, because false-a can be the number 0, or an empty string, etc. Simple existence can be truth-a. A “real” boolean will only be true or false.

1 Comments:

Time to share expertise, insights, tips, and tricks for using Java technology, leveraging the Java programming language, or extending the Java platform. Fingers crossed waiting for JavaOne India 2013 Hyderabad May 8th and 9th. Register here http://bit.ly/YMPeJ8 today and be part of JavaOne India.