JavaScript Quiz #3

Understanding JavaScript by example is useful for absorbing the different concepts of the language quickly. In this post, I will illustrate a quick JavaScript Quiz to understand how JavaScript (+) operator works. Assume that we have the following JavaScript code:

var object1 = {
    someVar: 2,
    someName: "object1",
    valueOf: function () {	
        return this.someVar;
    },
    toString: function () {	
        return this.someName;
    }
};

var result = "I equal " + object1;

alert(result); //What is the output of the alert?

What is the output of the alert?

Read the complete answer

Resetting dojox.mobile.ScrollableView to top

ScrollableView is a container widget which represents an entire mobile device screen, and has a touch scrolling capability. Sometimes, you may need to reset ScrollableView to the top or to any position in the mobile screen.
In order to achieve this requirement, you need to use its scrollTo() API, for example, scrolling to top can be done by setting x and y to zero as follows:

require(["dojox/mobile/parser", "dijit/registry", ..., "dojo/domReady!"], function(parser, registry) {
	//...
	var view = registry.byId("someViewID");
	view.scrollTo({x:0 ,y: 0});
	//...
});

Following this approach, you can scroll ScrollableView to any position you like by specifying a suitable x and y values.

JavaScript Quiz #2

Now, it is the time for the second JavaScript quiz.

Assume that we have the following JavaScript code:

var someVar = "1";
var someObject = {
	someVar: 2,
	someMethod: function () {
		var someVar = 3;
		var _this = this;
		
		setTimeout(function() {
			var result = _this.someVar + this.someVar;
			
			alert(result); //What is the value of result here?
			
			if (result > 20) {
				+result--;
			} else {
				+result++;
			}
			
			alert(result); //What is the value of result here?
			
		}, 10);		
	}
};

someObject.someMethod();

The question is what is the output in each alert and Why?
.
.
.
.
.
.
.
.
.
.
.
.
.
In order to understand how this JavaScript example will work, we should know the following:
1. How the JavaScript “this” keyword works.
2. How the JavaScript operators work.

I illustrated in details how the JavaScript “this” keyword works here, in summary, “this” evaluates to the object on which the method was invoked. This means that _this.someVar inside the setIimeout will be evaluated to 2.

It is important to understand how the + Arithmetic operator work, in the following line:

var result = _this.someVar + this.someVar;

The value of result in this line will be evaluated to: 2 + “1” = “21”. This is because the + Arithmetic JavaScript operator always favors String which means that if you have a numeric + String, the numeric operand will be converted to String and the result of the + Arithmetic operator will be a simple String concatenation.

Then coming to the next line:

result > 20

Here there is a comparison between both String and a numeric, unlike the + Arithmetic operator, the JavaScript Relational operators favor numeric, which means that result will be converted to integer so the comparison will be 21 > 20 which will be evaluated to true.

Finally in the following line:

+result--;

The + unary operator can be used to convert its operand to integer, however, it has no effect here as the evaluation of the expression the — post-increment operator is executed before it which will convert result to integer and decrement it by 1.

This is the explanation why the alerts will produce the following results in order:
1. 21
2. 20

This is all about this quiz. Stay tuned for the next one soon!

>>Edited in 01 April 2013.

Getting Yahoo! Weather from JavaScript ONLY

Getting weather information in mashup applications is a very common task. As you may know, Yahoo! thankfully provided a REST API that can be used in order to get weather information using location’s zip code.
In order to invoke the Yahoo! weather REST API from JavaScript client, you can either create an XHR request that talks with a local server proxy which deals with the Yahoo! weather REST API (in order to avoid the security exception of cross-domain Ajax requests on the JavaScript client) or to use JSONP which is supported by the Yahoo! Query Language. In this post, the second approach will be illustrated because it does not require any server side work.

Dojo has a "dojo/request/script" module that can handle interactions with JSONP endpoints as follows:

require(["dojo/request/script"], function(script){
  script.get(URL, {
    jsonp: "callback",
    preventCache: true,
    timeout: 3000
  }).then(function(response) {
    // Do something with the response data
  }, function(error) {
    // Handle the error
  });
});

script object has a get API that has two parameters:
1. JSONP Service URL.
2. JSON object with optional parameters. Optional parameters can be:
a. jsonp: The name of the JSONP query parameter.
b. preventCache for cache prevention.
c. timeout: The number of milliseconds to wait for the response. If this time passes the request is canceled and the promise rejected.

For the complete list of optional parameters, check Dojo documentation here.

This is all about what you need to know about this API. Now, let’s see how to retrieve the weather information of an example place (New Era – Michigan) which has the following zip code 49446.

var errorMessage = "Unable to get weather information.";

var zipcode = "49446"; //New Era - Michigan

var query = "q=" + escape(
		  "select item from weather.forecast where location") + 
		  "=\"" + zipcode + "\"";

var endPointURL = "http://query.yahooapis.com/v1/public/yql?" + query  + 
		  "&format=json";


script.get(endPointURL, {
	jsonp: "callback",
	preventCache: true,
	timeout: 3000
}).then(function(response) {
	try {
		document.getElementById("someDivID").innerHTML = response.query.results.channel.item.description;
	} catch (exception) {
		alert(errorMessage);
	}
}, function(error) {
	alert(errorMessage + " Make sure that your device is connected to the internet.");
	console.log(error); 
});

endPointURL includes the Yahoo! REST service URL with the needed parameters and the request timeout parameter is set to 3 seconds.

Once the JSON response is retrieved successfully from the server, it will look like the following:

dojo.io.script.jsonp_dojoIoScript2._jsonpCallback({"query":{"count":1,"created":"2013-03-18T02:34:06Z","lang":"en-US","results":{"channel":{"item":{"title":"Conditions for New Era, MI at 9:33 pm EDT","lat":"43.56","long":"-86.35","link":"http://us.rd.yahoo.com/dailynews/rss/weather/New_Era__MI/*http://weather.yahoo.com/forecast/USMI0597_f.html","pubDate":"Sun, 17 Mar 2013 9:33 pm EDT","condition":{"code":"33","date":"Sun, 17 Mar 2013 9:33 pm EDT","temp":"24","text":"Fair"},"description":"\n<img src=\"http://l.yimg.com/a/i/us/we/52/33.gif\"/><br />\n<b>Current Conditions:</b><br />\nFair, 24 F<BR />\n<BR /><b>Forecast:</b><BR />\nSun - Mostly Clear. High: 29 Low: 22<br />\nMon - PM Snow. High: 37 Low: 23<br />\n<br />\n<a href=\"http://us.rd.yahoo.com/dailynews/rss/weather/New_Era__MI/*http://weather.yahoo.com/forecast/USMI0597_f.html\">Full Forecast at Yahoo! Weather</a><BR/><BR/>\n(provided by <a href=\"http://www.weather.com\" >The Weather Channel</a>)<br/>\n","forecast":[{"code":"33","date":"17 Mar 2013","day":"Sun","high":"29","low":"22","text":"Mostly Clear"},{"code":"16","date":"18 Mar 2013","day":"Mon","high":"37","low":"23","text":"PM Snow"}],"guid":{"isPermaLink":"false","content":"USMI0597_2013_03_18_7_00_EDT"}}}}}});

This is why using the response.query.results.channel.item.description long expression will get the required weather information from the returned service response.

JavaScript Quiz #1

Having quizzes from time to time is very important in order to refresh our information. This is why I decided to post JavaScript quizzes in order to have a better understanding of JavaScript.

Assume that we have the following JavaScript code:

var someVar = 1;
var someObject = {
	someVar: 2,
	someMethod: function () {
		var someVar = 3;
		
		alert(this.someVar); //What is the result ???
		
		setTimeout(function(){
			alert(this.someVar); //What is the result ???
		}, 10);		
	}
};

someObject.someMethod();

The question is what is the output in each alert and Why?
.
.
.
.
.
.
.
.
.
.
.
.
.
In order to understand how this JavaScript example will work, we should know how the JavaScript “this” keyword works. It is important to know that within a body of JavaScript method, “this” evaluates to the object on which the method was invoked.

This mean in the “this.someVar” expression of the first alert, “this” will be evaluated to someObject object on which someMethod method was invoked, which will result in 2 (the value set in line 3).

In the “this.someVar” expression of the second alert, “this” will be evaluated to Window global object because of the window.setTimeout, which will result in 1 (the value set in line 1).

This is all about this quiz. Stay tuned for the next one soon!

Resolving the z-index problem in Android 2.x Browser

One of the alarming issues of the Android 2.x Browser is that it does not respect the z-index of input elements, this issue is described here in details:
http://code.google.com/p/android/issues/detail?id=6721.

This issue can actually be very blocker to you if your mobile web application contains many openers that utilize the z-index CSS property in order to appear on the top of the active mobile view. This is because when the application’s opener is active and due to this bug, you can find the underlying mobile view input elements highlighted (focused) on the top of the opener as shown in the figure below.
BUG

In order to resolve this issue, I applied the following solution that works with me:
1. When a new opener is opened:
All of the *relevant* underlying input elements inside the view must be disabled. Doing this fix will disable the keyboard interaction with the underlying input elements and in the same time will not allow these input elements to be *focused*.

2. When the opener is closed:
All of the disabled input elements in the first step can be re-enabled again.

The solution looks complex, however, it can help if you have a similar situation.

JavaScript Variable Scope confusion for Java Developers

Sometimes, the Java developers that are new to the JavaScript world have a confusion regarding the variable scoping in JavaScript. Let’s see an example that will illustrate this confusion, consider that we are having the following Simple JavaScript code:

<script>
var someVar = 0;

{
    var someVar = 100;
}

alert(someVar);
</script>

Some of the new JavaScript developers (from Java background) will expect that the result of the someVar will be 0, because the defined someVar variable inside the inline block will be ignored once the inline block ends.

In fact, the end result will be 100, This is because JavaScript does not have the concept of Java block scopes, JavaScript has only two scopes:
1. Global Scope.
2. Local Scope which is applied ONLY on the function(s) level (A single function or functions inside function) NOT on any other type of block(s) level (such as loops and inline blocks).

To be able to understand JavaScript local scope, Let’s introduce a new function to our original example:

{
    var someVar = 100;
    //someVar will be visible everyWhere ...
}

function someFunction() {
    var someVar = 10; 
	
    //someVar will be visible only here as 10 ...
}

alert(someVar);
someFunction();
alert(someVar);

The result will be:

100
100

someFunction defines a someVar variable and initializes it to 10, the someVar variable will be visible as long as we are in the someFunction‘s scope, when the someFunction ends, the someVar‘s function variable will not be available anymore, this is why the second alert will produce 100 which is the original value of someVar that is defined in the Global scope.

Checking the Local Storage limits across the browsers

One of the issues you may face during your daily job (if you are a web developer) is how to check the limits of the Local Storage across the different browsers. This is because there is no unified fixed storage quota for local storage across all the browsers, for example, Chrome local storage quota is 2.5 MB. In Firefox, it is 5 MB and in IE, it is 10 MB.

In order to check if the local storage reaches its maximum quota, it will not be efficient to depend on the mentioned quota sizes on every browser, other than this, I prefer to do this programmatic-ally as shown in the following JavaScript function:

function saveInLocalStorage(name, value) {
    try {
        localStorage.name = value;
        return true;
    } catch (e) {
        return false;
    }
}

Using saveInLocalStorage method, you can safely store your local storage entry, and if saveInLocalStorage method returns false, this is an indicator that the browser’s local storage maximum quota is reached, and you will need to show the user an error message asking him to free some of the saved entries in the local storage.

These are my thoughts regarding how to implement this requirement, if you have other thoughts, let me know.