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.