JavaScript Quiz #6

Assume that we have the following short JavaScript code:

<script>
	var result = [12 + 21]['valueOf']()['length'];
	alert(result); //What is the output of the alert?

	result = [12 + 21]['valueOf']['length'];
	alert(result); //What is the output of the alert? 
</script>

What is the output of each alert?
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
The result will be as follows 1 then 0. The first expression (the easy one) will be executed as follows:

var result = [12 + 21]['valueOf']()['length'];

The expression can be read as [33].valueOf().length which means that .length property will print the length of the valueOf() call to array [33] which is 1. Note that the [33].valueOf will return [33].

The second expression is the tricky part:

var result = [12 + 21]['valueOf']['length'];

The expression can be read as follows [33].valueOf.length. This is really completely different from the first expression because in this case the .length property will print the number of arguments of the valueOf method which is zero. This is because if the .length property is attached to a method then it will print the number of arguments of the method.

JavaScript Quiz #5

This quiz covers some of the JavaScript operators in order to explain they can work together inside expressions. Assume that we have the following JavaScript code:

var object1 = {
    valueOf: function () {
	return 10;
    },
    toString: function () {
	return "object1";
    }
};

var object2 = {
    valueOf: function () {
	return 20;
    },
    toString: function () {
	return "object2";
    }
};

var object3 = {
    valueOf: function () {
	return 30;
    },
    toString: function () {
	return "object3";
    }
};

var result = (object2, object1, object3) + object1 +-- object1; 
alert(result);

What is the output of the alert?
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
The output of the alert is 49. Let’s analyze this quiz. In the following expression:

(object2, object1, object3)

In order to know the result of this expression, we have to know how expressions work with the comma operator, if we have an expression that contains many comma operators then this expression will be evaluated to the last mentioned value. This means that
(object2, object1, object3) will be evaluated to object3. We will then have the following reduced expression:

object3 + object1 +-- object1

In this expression, we have two main operators:
1. + operator.
2. — prefix operator.

The execution order will be as follows:
1. — prefix operator.
2. + operator.

To get the complete list of operator precedence, check https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Operator_Precedence.

The execution order means that the expression evaluation will start by:

-- object1

The — prefix operator will be applied on object1 which will result in calling the valueOf method of object1, This means that the result will be 10 – 1 = 9.

Then the evaluation execution continues by adding object3 + object1 to the previous result as follows:

object3 + object1 + 9

Now, we come to the simplest part of the quiz, the valueOf methods of object1 and object3 are called, which means that the final result will be 30 + 10 + 9 = 49.

The original addition rule according to Ecma-262 specification is as follows for your reference:
“The addition operator either performs string concatenation or numeric addition.

The production AdditiveExpression : AdditiveExpression + MultiplicativeExpression is evaluated as follows:
1. Let lref be the result of evaluating AdditiveExpression.
2. Let lval be GetValue(lref).
3. Let rref be the result of evaluating MultiplicativeExpression.
4. Let rval be GetValue(rref).
5. Let lprim be ToPrimitive(lval).
6. Let rprim be ToPrimitive(rval).
7. If Type(lprim) is String or Type(rprim) is String, then
a. Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)
8. Return the result of applying the addition operation to ToNumber(lprim) and ToNumber(rprim).

In order to check previous quizzes:
1. JavaScript Quiz #4
2. JavaScript Quiz #3
3. JavaScript Quiz #2
4. JavaScript Quiz #1

JavaScript Quiz #4

Understanding JavaScript by example is useful for absorbing the different concepts of the language quickly. In this post, I will illustrate a JavaScript Quiz to understand how the JavaScript operators work together. Assume that we have the following JavaScript code:

var object1 = {
    valueOf: function () {
        return 1;
    },
    toString: function () {
        return "object1";
    }
};

var object2 = {
    valueOf: function () {
        return 2;
    },
    toString: function () {
        return "object2";
    }
};

alert((object2 > object1 +-- object1) + true); //What is the output of the alert?

What is the output of the alert?
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
The output of the alert is 2. In order to understand why we have this result, we should know how the different JavaScript operators work together. Let’s analyze this quiz.
In the following expression:

(object2 > object1 +-- object1) + true

We have two main part, the first part is the expression between brackets and the second one is the boolean true operand. Let’s see how the first part will be evaluated.

object2 > object1 +-- object1

In this expression, we have three main operators:
1. > operator.
2. + operator.
3. — prefix operator.

The execution order will be as follows:
1. — prefix operator.
2. + operator.
3. > operator.

To get the complete list of operator precedence, check https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Operator_Precedence.

The execution order means that the expression evaluation will start by:

-- object1

The — prefix operator will be applied on object1 which will result in calling the valueOf method of object1, which means that the result will be 1 – 1 = 0.

Then the evaluation continues by adding object1 to the previous result:

object1 + 0

The valueOf method of object1 is called again, which means that the result will be 1 + 0 = 1.

Then the comparison will be performed as follows:

object2 > 1

In order to perform the comparison, the valueOf method of object2 is called, which means that the result will be 2 > 1 = true.

Then finally we will have the following:

true + true

According to Ecma-262, if we have an arithmetic plus operator and none of its operand are of type String, then both operands will be converted to numeric and the addition operation is performed. In JavaScript when true is converted to Numeric, the result will be 1 (while false is converted to 0).

The original addition rule according to Ecma-262 specification is as follows for your reference:
“The addition operator either performs string concatenation or numeric addition.

The production AdditiveExpression : AdditiveExpression + MultiplicativeExpression is evaluated as follows:
1. Let lref be the result of evaluating AdditiveExpression.
2. Let lval be GetValue(lref).
3. Let rref be the result of evaluating MultiplicativeExpression.
4. Let rval be GetValue(rref).
5. Let lprim be ToPrimitive(lval).
6. Let rprim be ToPrimitive(rval).
7. If Type(lprim) is String or Type(rprim) is String, then
a. Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)
8. Return the result of applying the addition operation to ToNumber(lprim) and ToNumber(rprim).

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?
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
The output of the alert is “I equal 2″. In order to understand why we have this result, we should know how JavaScript (+) operator works. Normally, as you may know in JavaScript, the (+) operator favors String, which means that if we have a String + Number then Number will be converted to a String and the result will be a concatenation between the two String objects.

In case that we have a String + Object, then toString() method will be called on the Object‘s valueOf() method, this is why in the line:

"I equal " + object1;

The right hand side value of the expression will be evaluated to “2” which will be concatenated with the left hand side value to have finally the result “I equal 2″.

The original rule according to Ecma-262 specification is as follows for your reference:
“The addition operator either performs string concatenation or numeric addition.

The production AdditiveExpression : AdditiveExpression + MultiplicativeExpression is evaluated as follows:
1. Let lref be the result of evaluating AdditiveExpression.
2. Let lval be GetValue(lref).
3. Let rref be the result of evaluating MultiplicativeExpression.
4. Let rval be GetValue(rref).
5. Let lprim be ToPrimitive(lval).
6. Let rprim be ToPrimitive(rval).
7. If Type(lprim) is String or Type(rprim) is String, then
a. Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)
8. Return the result of applying the addition operation to ToNumber(lprim) and ToNumber(rprim).”

In order to get Quiz #1 and #2, check:
1. JavaScript Quiz #1:
http://www.technicaladvices.com/2013/03/14/javascript-quiz-1/
2. JavaScript Quiz #2
http://www.technicaladvices.com/2013/03/28/javascript-quiz-2/

Tamer Safwat’s review about JavaScript Unit Testing Book

Attached below the review of Tamer Safwat (Staff Software Engineer at Disney) about the “JavaScript Unit Testing” book:

JavaScript Unit Testing

JavaScript Unit Testing Book

Great book
“This is the most comprehensive and practical JavaScript unit testing reference I found and maybe the only one out there.

Not only the author is covering the most popular frameworks for JavaScript unit testing, he is also covering tools and plugins required to build an efficient testing environment.

The book has plenty of code samples which not only explain different unit testing scenarios but also explain many JavaScript and web programming best practices and concepts.

Overall this is a great book and a must have for anyone doing serious JavaScript work.”

Reference:
http://www.amazon.com/dp/1782160620/

The book on PacktPub:
http://www.packtpub.com/javascript-unit-testing/book

JavaScript Unit Testing Book Review by Mihai

Attached below the review of Mihai about the “JavaScript Unit Testing” book:

JavaScript Unit Testing

JavaScript Unit Testing Book

Great Book!
“I’ve just read the JavaScipt Unit Testing book and I found it very useful for professionals that need to implement or upgrade their strategy for Unit Testing.
The greatest gain, I believe, is the excellent explanation on how to use tools for Unit Testing like Jasmine, YUI, QUnit and JsTestDriver.
Great book!”

Reference:
http://www.amazon.co.uk/review/RWDCG4MJYFNZP/ref=cm_cr_dp_title?ie=UTF8&ASIN=1782160620&channel=detail-glance&nodeID=266239&store=books

The book on PacktPub:
http://www.packtpub.com/javascript-unit-testing/book

JavaScript Unit Testing Book Review by J. Powell

Attached below the review of J. Powell about the “JavaScript Unit Testing” book:

JavaScript Unit Testing

JavaScript Unit Testing Book

Great Book covering a critical topic for web applications
“The importance of JavaScript testing in single page web applications can not be overstated. When the majority of your codebase is moved to client side JavaScript, it’s more critical then ever to automate your client side testing environment in order to have a stable application. JavaScript Unit Testing teaches you to take your Test Driven and Behavior Driven development practices and apply them to the client side.”

Reference:
http://www.amazon.com/dp/1782160620/

The book on PacktPub:
http://www.packtpub.com/javascript-unit-testing/book

Review #3 about the JavaScript Unit Testing Book

Attached below the review of Werner Punz (Senior software developer for Irian GmbH. Vienna, an Apache MyFaces Committer Member of the JSF Expert Group and a JavaScript expert) about the “JavaScript Unit Testing” book:

JavaScript Unit Testing

JavaScript Unit Testing Book

Just read the book
“The book is very good, it covers the theory behind unit testing and then goes into details by applying various unit testing frameworks in a small and a real world Ajax example.
The testframeworks covered are

– Jasmine
– YUI Test
– QUnit
-JSTestdriver

This book is a must read for everyone interested into Javascript unit testing, especially if you have to cover asynchronousity via Ajax (which is a key focal point through the entire book, in the more complex example).

Overall a very good book. Five stars from me.”

Reference:
http://www.amazon.com/dp/1782160620/

The book on PacktPub:
http://www.packtpub.com/javascript-unit-testing/book

Integrating JsTestDriver tests with Hudson

JsTestDriver is one of the most efficient JavaScript unit testing tools. Integrating JsTestDriver with continuous integration tools is a mandatory step for ensuring the web application quality. In this post, I will illustrate how this sort of integration can be done between JsTestDriver and Hudson.

Installing Hudson

To install Hudson on your machine, you need to download it from http://hudson-ci.org/.

Run the following command to start Hudson:

java -jar hudson-2.2.0.war

You can start launching Hudson by typing the following address in your browser:

http://localhost:8080/

You should now be redirected to the Hudson home page.

Creating Hudson Job

First of all, you need to create a new Job in Hudson. You can do this by clicking on “New Job” and entering the Job name and selecting “Build a free-style software project” as shown in the figure below:

Configuring JsTestDriver with Hudson

Click the “Configure” link of the project. In the configuration page, enter the project description. In order to run the job periodically, you need to configure the “Build Triggers”. Check the “Build periodically” option and enter the cron-like expression. To run the job every 5 mins past the hour (for example), enter the following expression 5 * * * * as shown below in the figure:

In order to execute the JsTestDriver test command, you need to configure the “Build” section. There are many ways to do so, you can either add “Execute Shell”, “Invoke Ant or Maven2 or Maven3″, or “Execute Windows Batch command”. The latter case can be used when you are working on Windows environment. For the case of this example, I use the “Execute Windows Batch command” option and specify the path of the batch file as shown in the screenshot below:

The batch file has the following content:

java -jar JsTestDriver-1.3.4.b.jar 
      --config jsTestDriver.conf 
      --tests all 
      --testOutput c:/outputFolder 
      --reset

For the matter of simplicity, I assume that the JsTestDriver server is already started and some browsers are already captured. This step is not included in this post, however, This step also can be automated if required.

Testing the integration of JsTestDriver with Hudson

In order to test the integration of JsTestDriver with Hudson, this can be done by manually or automatically (as indicated in the “Build periodically” option). To test the integration manually, click on the “Build Now” link as shown in the screenshot below:

Click the “console output” link to check the output of the results:

setting runnermode QUIET
Firefox: Reset
...
Total 3 tests (Passed: 3; Fails: 0; Errors: 0) (3.00 ms)
  Firefox 12.0 Windows: Run 3 tests (Passed: 3; Fails: 0; Errors 0) (3.00 ms)

Notices

You may face this error while trying to run a new Job:

hudson java.io.IOException: Cannot run program "sh"

In order to fix this error, check this post:
http://www.technicaladvices.com/2012/05/04/hudson-java-io-ioexception-cannot-run-program-sh-resolution/.

Review #2 about the JavaScript Unit Testing Book

Attached below the review of Juanjo Fern├índez about the “JavaScript Unit Testing” book:

JavaScript Unit Testing

JavaScript Unit Testing Book

Improving your JavaScript code
“I suppose at least in a generic way you know what is unit testing, but to sum it up in a few words, according to Wikipedia:

Unit testing is a method by which individual units of source code, sets of one or more computer program modules together with associated control data, usage procedures, and operating procedures, are tested to determine if they are fit for use.

By starting an application development, when it has relatively few lines of code all “fits” perfectly, but later when you want to add, modify, or delete certain functionality, this can become a big problem since when changing anything probably you will be breaking a few by the way.

Thanks to unit testing you can modify any module in your code, launch the tests, check failures, correct, and ready. Everything will still work in a clean, quick, and tidy way.

Once completed this short introduction, I’m going to review a book I’ve been reading these days and is about this theme: JavaScript Unit Testing:

Chapter 1 – Unit Testing JavaScript Applications: You’ll find the only theoretical part of the entire book on the first pages of this chapter, where you’ll learn what are the unit tests, why they are needed, and different approaches to create the tests: traditional unit testing and TDD.

Once this part is completed, you’ll see how works the application on which you’re going to make all the tests you’ll find in the book. It’s an application with the backend programmed in Java and a good amount of JavaScript in the frontend, that it really is what you’ll be interested to make the tests. The application allows you to complete a new user registration, authenticate and check the weather in some cities.

Don’t be scared by the fact that the application’s backend is programmed in Java: you won’t see anything of Java throughout the entire book however if you want to run the application in your computer, you’ll need to install Apache Tomcat.

Chapter 2 – Jasmine: Jasmine is a behaviour-driven development framework for testing JavaScript code. The behaviour-driven development is based on TDD.

The Jasmine test cases give more importance to the application business value over the technical details. Also are written in natural language so they can be understood by people without technical background.

In this chapter you’ll learn to install, configure and write tests with Jasmine on the application JavaScript code you saw in the first chapter, including Ajax.

Finally you’ll use together jQuery and Jasmine thanks to an available plugin that allows an easy integration between these 2 frameworks.

Chapter 3 – YUI Test: In this chapter you’ll learn to use one of the most popular unit testing frameworks: YUI Test.

YUI Test is part of the open source library for JavaScript and CSS called YUI, but with YUI Test you can test any JavaScript code, even if you don’t use YUI.

As with the previous chapter with Jasmine, in this case you’ll make unit testing with YUI Test on simple JavaScript code for later create the necessary unit testing for the application included with the book.

In addition to this you’ll see how to automate your unit testing integrating YUI Test with Selenium Driver.

Chapter 4 – QUnit: The third unit testing framework that you’ll learn to use is QUnit. It’s the framework used by all the projects related to jQuery (jQuery, jQuery UI, and jQuery Mobile) but you can use it to test any JavaScript code.

QUnit is very popular and has a simple syntax that allows you to run the tests from a browser.

Like in previous chapters, you’ll see how to install and configure QUnit, run your firsts tests, and once you’ve got a solid basis create the necessary tests for the weather application.

Chapter 5 – JsTestDriver: JsTestDriver (JSTD) is one of the most powerful frameworks for unit testing because in addition to the framework, it incorporates a test runner that can run other unit testing frameworks. All contained in a JAR file that includes everything you need to start to create your tests.

This last chapter goes similar path than previous: you’ll learn to install and configure JsTestDriver, you’ll make basic unit testing to learn its functioning and at last you’ll create the tests for the application you already know, but also you’ll learn to generate complete reports with the testing data, and to integrate JSTD with other JavaScript frameworks like Jasmine or QUnit.

Finally you’ll see how to integrate JSTD with the Eclipse IDE thanks to the JSTD Eclipse plugin.

It’s a short book compared with other books published by PacktPub but the content quality hasn’t been reduced. In any case I’ve missed information about other frameworks based on node.js that are becoming very popular like Mocha or CasperJS.

Another thing that could have improved is the application included with the book code. Since it’s a book about JavaScript it should be an application developed with node.js and not with Java, further it would have been easier to run on your computer, since to run the included application you need to install Apache Tomcat.

Beyond these minor flaws that I mentioned, It’s a highly recommended book, which includes a wealth of information and code from the most popular unit testing frameworks in the JavaScript community.

When you have finished reading it you will have a strong foundation to begin creating unit tests for your applications, which will improve your code and will optimize the time that you spend to modify existing applications.”

Reference:
http://www.amazon.com/gp/cdp/member-reviews/A3EZCWDMX7BCAQ/ref=cm_pdp_rev_title_1?ie=UTF8&sort_by=MostRecentReview#R2ZGNORO9BNK6K

The book on PacktPub:
http://www.packtpub.com/javascript-unit-testing/book