Exploring JavaScript’s undefined

When we are working with JavaScript operators, we need to pay utmost attention on how we use them. For example let’s create a simple function which takes two arguments a, b.

function foo(a, b) {
    a = a || "value";
    b = b || 4;
    
    alert("a is: "+ a + "; b is: " + b);
}

foo("", 0);


Stop..!! Don’t jump on the result. Go through the function and what has been passed as arguments to the function. Now if your answer is 0 then you are wrong. Rather you get a is: value; b is 4. Wait. What? Why is that? In JavaScript, we need to verify whether passed arguments are of valid inputs are not. Certainly, empty string isn’t a valid input and 0 isn’t too. Hence we get the result that we didn’t expect.

Let us go on something which is much more interesting. Suppose I have this code written:

1: var isDefined = function () {
2:     var undefined = 1;
3:     return function (x) {
4:         return x !== undefined;
5:     };
6: }();

7: alert(isDefined(undefined));
8: alert(isDefined(1));


So what does the above alerts return? Before that, let us first go through each line of code that is written.

  1. In line 2, a variable named undefined is declared and has been initialized with a value 1. Yes I know what you are thinking now. Can we declare undefined as a variable? And the answer is Yes. We can.!! undefined is not a JavaScript keyword. Rather, it can be specified as:

    The Undefined type has exactly one value, called undefined. Any variable that has not been assigned a value has the value undefined.

  2. And in line 4, we are just checking the condition with the argument passed in the function.
  3. At line 7, we are alerting the value that is passed as an argument to the function isDefined. We expect it as true because a variable is defined with undefined and it has value 1 which is not equal to undefined which is passed as an argument through the function. But the result is false. What..? Why is that? Because, when you write undefined in a JavaScript program, you actually refer to a previously bound name. By default this will result in looking up the name undefined on the global object, which is what most people expect.
  4. Now what will line 8 alert? Obviously true.


So how can we fix this? If you get it right, you should stat using void 0 which always yields the undefined value. Now rewrite the function as shown below:

1: var isDefined = function () {
2:     var undefined = 1;
3:     return function (x) {
4:         return x !== void 0;
5:     };
6: }();

7: alert(isDefined(undefined));
8: alert(isDefined(1));


Now line 7 alerts true as expected and line 8 alerts false.

By
Uma Maheswar

JavaScript Event Simulators in Selenium

Each browser has their own WebDrivers. Chrome has Chrome WebDriver, Mozilla has Gecko and Internet Explorer has IE WebDriver. So why are these webdrivers used for? The answer is, if you want to automate a web application, there has to be compatibility with the browser on which you want to automate your web application. Hence you need webdrivers.

Now the next problem we encounter as we start using these webdrivers is that:

  1. In some of the browser versions (old or new), you’ll encounter compatibility issue either with the browser or with the selenium itself. Suppose if the automation script is totally written on a specified version of selenium, there’s always a confusion to either update the selenium or the driver. With either of them, there’s no guarantee that the automation scripts written will work as expected.
  2. Features that your web application supports may not work with the webdriver that you have chosen and also with the version of Selenium.
  3. There is no proper documentation on how to include or use JavaScript with the arguments of Selenium and also there is no proper documentation on how to work with JavaScript simulators when above 1 & 2 points were encountered.


This post will ensure that the all the events were handled using JavaScript without using any predefined functions / methods that are present in the Selenium documentation. One can write JavaScript function and then execute it as Selenium supports JavaScript and also web browsers has their own set of drivers for executing Selenium files on web browser.

It has to be kept in mind that, when we say JavaScript is used, one has to take care of methods that a browser supports. Old browsers such as IE 8 or 9 may not support all the functions or methods that you use.

So how do we use event simulators in Selenium file?

Suppose say we want to perform a click operation on an element. We can do that quite easily like this:

function simulateSingleClick(el) {
    var evt = document.createEvent('MouseEvents');
    evt.initEvent('click', true, true);
    return el.dispatchEvent(evt);
}

simulateSingleClick(document.getElementById('id'));


Let us go through each line of code written above in simulateSingleClick function.

  1. The function takes one argument which is an element on which the event has to be triggered.
  2. An event is created using document.createEvent method which takes type as an argument. It specifies type of event one wishes to trigger. Here, we are intended to use MouseEvents.
  3. After creating an event, event has to be initiated. This is done by using evt.initEvent method. This method takes three arguments in which one is event type. Second is event bubble which is a boolean value and the third argument is cancelable which is also a boolean value. We pass boolean values as true because we want to event bubble to happen on the passed element to the function and it should not be canceled.
  4. After the event has been initiated, event has to be dispatched on the selected element. So we use element.dispatchEvent method which takes one argument which is event that has been initiated.
  5. And we return the dispatched element.


So how simple is that.

In same way, we can write any MouseEvents simulator using above function. Just replace the event type that has to be triggered on the selected or passed element. If one has to double click on an element, you can do like this:

function simulateDoubleClick(el) {
    var evt = document.createEvent('MouseEvents');
    evt.initEvent('dblclick', true, true);
    return el.dispatchEvent(evt);
}

simulateDoubleClick(document.getElementById('id'));


You can refer this link for applicable events that are supported. (Mouse Events)

So how do we use this function in Selenium file?

Quite simple. Just include this function as inline in the Selenium file using Selenium’s execute script function.

For example:

driver.executeScript("function simulateSingleClick(el) {var evt = document.createEvent('MouseEvents');evt.initEvent('click', true, true); el.dispatchEvent(evt);}simulateSingleClick(document.getElementById('id'));


For reference: Dispatch Event

-By
Uma Maheswar
Helical IT Solution

Create A Custom Table Report using Helical Insight (Dynamically Picking the Columns Names and Data)

Create A Custom Table Report using HI (Dynamically Picking the Columns Names and Data)

If you have already had a Hands-On experience on the Helical Insight Tool [HI tool] then this blog would be helpful

For a creating a report there are 4 files required
1. EFW
2. HTML
3. EFWD
4. EFWVF

the Report Layout lies on the HTML page, the SQL queries lies within the EFWD file and the visualization lies in the EFWVF File.
Hence once the Query is fired it comes to the visualization file to create a table as that’s our goal. With the help of the following code below it can be created with ease.

The below code here is a template of our EFWVF looks like
<Charts>
<Chart id=”1″>
<prop>
<name>Table</name>
<type>Custom</type>
<DataSource>1</DataSource>
<script>

//Your Visualization Code Goes Here

</script>
</prop>
</Chart>
</Charts>

Chart ID here is 1 which is unique
Type is of custom
DataSource 1 is the Unique ID defined in the EFWVF File. ie (<DataMap id=”1″ )
Now within the <script> </script>
we Paste the following:

<![CDATA[
//The If Block Does Return A Message NO Data when there is No Data
if(data.length == 0)
{
$(‘#chart_1′).html(“<div ><h4 style=’text-align:CENTER;color:black; padding-top:60px;’>No Data Available For Current Selection</h4></div>”);
return;
}
//The Else Block Returns The Table if there is a Table
else
{
//Here the funtion Tabluate Returns the Data in Tabular Form
function tabulate(elem, data, columns)
//Function Start
{
var table = d3.select(elem).append(“table”)
.attr(“class”,” table display compact width:100%;cellspacing:1 “)
.attr(“id”,”table”)
thead = table.append(“thead”),
tbody = table.append(“tbody”);

//Append the header row
thead.append(“tr”)
.selectAll(“th”)
.data(columns)
.enter()
.append(“th”)
.text(function(column) { return column; })
.attr(‘class’, function(d, i){ return “colH_” + i; })
.style(‘background-color’,’#ededed’)
.style(‘color’,’black’)
.style(‘@media print’,’display:none’)
.style(‘padding-left’,’25px’);

// create a row for each object in the data
var rows = tbody.selectAll(“tr”)
.data(data)
.enter()
.append(“tr”);

// create a cell in each row for each column
var cells = rows.selectAll(“td”)
.data(function(row) {
return columns.map(function(column) {
return {column: column, value: row[column]};
});
})
.enter()
.append(“td”)
.text(function(d) { return d.value; })
.attr(‘class’, function(d, i){ return “col_” + i; })
.attr(‘align’, ‘left’)
return table;
//Function END
}

//Render the table
//Object.keys(data[0]) is the Data to fetch the Column Header
//data has the data of the Table
console.log(Object.keys(data[0]));
var subjectTable = tabulate( ‘#chart_1’, data, Object.keys(data[0]));
}
]]>
Save it in the same Directory with rest of the file

Run your report on HI and you get a table.

Keep in mind you can change the query and still get the new columns from the new query.

Thanks
Sohail Izebhijie

Event Delegation

First let’s create HTML of an unordered list (ul).
HTML

<ul id="todo-app">
	<li class="item">Item 1</li>
        <li class="item">Item 2</li>
        <li class="item">Item 3</li>
        <li class="item">Item 4</li>
</ul>

Event Delegation technique:

Suppose if you have attached the event listener click on li rather than on ul, then you are attaching the listener to every li element and if there are n number of li elements, this is not the efficient way to attach the event listeners. Rather attach the event listener to ul and call or target only specific li element as listener. This is called event delegation.

Wrong implementation:

document.addEventListener('DOMContentLoaded', function() {
  
  let app = document.getElementById('todo-app');
  let items = app.getElementsByClassName('item');
  
  // attach event listener to each item
  for (let item of items) {
    item.addEventListener('click', function() {
      console.log('Wrong: You clicked on item: ' + item.innerHTML);
    });
  }
  
});

Correct implementation:

document.addEventListener("DOMContentLoaded", function() {
  let app = document.getElementById("todo-app");
  
  app.addEventListener("click", function(e) {
    if(e.target && e.target.nodeName === "LI") {
      let item = e.target;
      console.log("Correct: You clicked on: " + item.innerHTML);
    }
  });
});



Check this codepen link for further understanding: Event Delegation

-By
Uma Maheswar
Helical IT Solution

Functions in JavaScript

Consider the given code below:

1:    function doSomething(a) {
2:        function doSomethingElse(a) {
3:            return a - 1;
4:        }
5:        var b;
6:        b = a + doSomethingElse( a * 2 );
7:        console.log( b * 3 );
8:    }

doSomething( 2 );

By considering above code, if you are learning JavaScript, you might get 9 as your answer. But think twice. Or let me explain you in a better way.

First you have to understand that JavaScript treats functions as its first class citizens. Meaning, JavaScript compiler will first compile functions.

Hence in the above code, let me breakdown into smaller segments and see what is happening where. So firstly we start at line 6 which says:

b = a + doSomethingElse( a * 2 );

Again narrow down line 6 and consider:

doSomethingElse( a * 2 );
// returns 4

Now the JavaScript compiler goes to line 2:

function doSomethingElse(a) {
    return a - 1;
}

// returns 3 because now a is 4 but not 2

And again compiler comes back to line 6 and re-compiles the code:

b = a + doSomethingElse( a * 2 );

Now b returns 5 because doSomethingElse( a * 2 ); is 3 now (which is returned from above function doSomethingElse)

Hence the result is 5 * 3 = 15.

As a beginner, it is recommended to understand what is happening at the background and visualize it before start coding actual code. Cheers..!! Happy Coding.

-By
Uma Maheswar
Helical IT Solution

JavaScript Timers

It is well known fact that JavaScript by nature is single-threaded which says that only one part of JavaScript code executes at a time. And interesting thing about timers is, they gets executed irrespective of other threads that are already in queue and also never interrupts another currently-running timer.

It is important for a complex JavaScript application not to become unresponsive to the user causing the browser to hang and eventually suspend all the updates of the page to be rendered while JavaScript is executing. It is therefore a fact that the complex operations should be managed in portions rather than a bulk.

Since JavaScript timers has the capability to suspend execution of a piece of code until a later time, this prevents the browsers from hanging. By considering this point, what we can do is to convert the bulk of code into loops and operate without blocking operations. Let’s consider an example to explain this:

<table>
    <tbody></tbody>
</table>

<script>
    var table = document.getElementsByTagName("tbody")[0];
        for ( var i = 0; i < 2000; i++ ) {
	    var tr = document.createElement("tr");
            for ( var t = 0; t < 6; t++ ) {
		var td = document.createElement("td");
  	        td.appendChild( document.createTextNode("" + t) );
  	        tr.appendChild( td );
            }
	table.appendChild( tr );
    }
</script>



In the above example,we are creating large amount of DOM nodes for populating a table with numbers. This is a expensive execution and will definitely allows the browser to hang. Now if we introduce timers into this situation to achieve a different, and perhaps a better solution to the above problem can be achieved. Check this code:

<table>
    <tbody></tbody>
</table>

<script>
    var table = document.getElementsByTagName("tbody")[0];
    var i =0, max = 1999;

    setTimeout(function() {
        for ( var step = i + 500; i < step; i++ ) {
            var tr = document.createElement("tr");
            for ( var t = 0; t < 6; t++ ) {
		var td = document.createElement("td");
  	        td.appendChild( document.createTextNode("" + t) );
  	        tr.appendChild( td );
            }
            table.appendChild( tr );
        }

        if(i < max) {
            setTimeout( arguments.callee, 0);
        }
    }, 0);
</script>



In the above modified example, what we have done is, we broke up our intense operation into smaller operations and each creates equal number of DOM nodes. Even if worst case is considered, operations will be further broken and increasing number of DOM nodes for each operation. It has to be noted that we don’t execute the above code in an infinite loop. Now the browser gets updated every once a while, not allowing the user to see these types of update that occur. But, it is important to remember that they occur.

In case of any doubt, please go through this video which explains how javascript timers work regarding setting setTimeout to 0.

JavaScript Event-Loop

-By
Uma Maheswar
Helical IT Solution

Primitive Wrapper Types in JS

In this post, I’m going to focus on basic concepts of JavaScript. So we are going to learn the concept of primitive wrapper types in JavaScript which is confusing to most.

So, there are three primitive wrapper types and they are: 1: String, 2: Number and 3: Boolean. And these primitive wrapper types are reference types that are automatically created behind the scenes whenever these primitive wrappers types are read. Let’s consider an example to explain our point.

var name = "Lorem";
var firstChar = name.charAt(0);
console.log(firstChar);     // "L"

In the first line of the above code, a primitive string value has been assigned to name. The second line treats name like an object and calls charAt(0) using dot notation.

Now let us examine behind the scenes of the above code:

// what the JavaScript engine does
var name = "Lorem";
vat temp = new String(name);
var firstChar = name.charAt(0);
temp = null;
console.log(firstChar);     // "L"

Since the second line in the above code uses a string (a primitive) like an object, the JavaScript engine creates an instance of Sting so that charAt(0) will work. The Sting object exists only for one statement before it’s destroyed (a process which is called autoboxing). At this point, since we have said that it is an object, we might consider to add a property to it. So let us give it a try:

var name = "Lorem";
name.last = "Ipsum";

console.log(name.last);     // undefined

The above code tries to add the property last to the string name. And looking at the code, it just looks fine but wait, What happened? Why didn’t it work? When we are working with regular objects, we are free to add properties at any time and they stay until you manually remove them. But with primitive wrapper types, properties seem to disappear because the object on which the property was assigned is being destroyed immediately afterward.

And this happens in JavaScript engine:

// what the JavaScript engine does
var name = "Lorem";
vat temp = new String(name);
name.last = "Ipsum";
temp = null;                // temporary object destroyed

var temp = new String(name);
console.log(temp.last);     // undefined
temp = null;

We can see what JavaScript engine has done. Instead of assigning a new property to a string, the code has actually creates a new property on a temporary object that is already destroyed. And when you try to access that property later, a different object is temporarily created and the new property doesn’t exist there. Although reference values are created automatically for primitive values, when instanceof checks for these types of values, the result is false.

var name = "Lorem";
var count = 5;
var found = false;

console.log(name instanceof String);      //false
console.log(name instanceof Number);      //false
console.log(name instanceof Boolean);      //false

The instanceof operator returns false because a temporary object is created only when a value is read. Because instanceof doesn’t actually read anything, no temporary objects are created, and this tells us that values aren’t instances of primitive wrapper types. It has to be noted that we cannot use String, Number and Boolean objects as you would primitive values. Even though the typeof evaluated to true.

-By
Uma Maheswar
Helical IT Solution

Document Fragments

The one of the most underrated feature of JavaScript is DocumentFragment. DocumentFragment is a DOM Node-like parent which has node-like properties/methods and is not a part of the actual DOM tree. It can be used for better performance. A DocumentFragment can be created using document.createDocumentFragment method.

Example Usage

Let us assume that we have to create a long list using ul.

<ul is="list"></ul>

Since DOM mutations are very expensive, we have to minimize the number of mutations possible. So instead of appending the items to ul directly, we will use a DocumentFragment.

var fragment = document.createDocumentFragment();

This DocumentFragment will act as DOM node on which we can attach our elements

for (var i = 0; i < 1000; i++) {
  var li = document.createElement("li");
  li.innerHTML = "Item #" + i;
  fragment.append(li);
}

Now we can append the DocumentFragment to ul.

document.getElementById("list").appendChild(fragment).

Using DocumentFragment is much faster than repeated single DOM node operations.

Arrays in JavaScript

Here is the question.
Suppose you are given two arrays as key, value pairs and asked you to associate them as Object with the same, who would you do that? So, here is the solution for it.

    function associateArrays(keys, values) {
        if(!Array.isArray(keys) || !Array.isArray(values)) {
            throw new TypeError("Expected two Arrays");
        }
        var result = {};
        for(var i = 0; i < keys.length; i++) {
            result(keys[i]) = values[i];
        }
        return result;
    }


    var split = associateArrays(["0", "1", "2"], ["a", "b", "c"]);
    split;
    //Object {0: "a", 1: "b", 2: "c"}



Here is another question.
Suppose say that you are given an array and asked to multiply each item in the array and return the result. SO here is the solution for it.

    function multipleArrayItems(arr) {
        if(!Array.isArray(arr)) {
            throw new TypeError("Expected an array");
        }
        if(arr.length < 2) {
            throw new TypeError("The array should at least have 2 items");
        }
        var product = arr[0];
        for(var i = 0; i < arr.length; i++) {
            product *= arr[i];
        }
        return product;
    }


    var product = multipleArrayItems([2, 2, 4, 4]);
    product; // 64


-By
Uma Maheswar
Helical IT Solution

Why Browser Detection is Bad ?

It is against the spirit of web standards

The whole reason that web standards exist is so that we don’t have to write specific code for specific environments. We should write code that adheres establishment of standards and software in charge of displaying our code should display it as the standards dictate.

It relies on the browser user-agent string,which has a hilariously disastrous history and it is easily spoofable. Also tt can hinder devices

Example:

you detect for the iPhone and serve is special content. Now the iPhone can never see the web page as other browsers see it, despite it being fully capable of doing so.

why we do it?

We do it because different browsers handle things differently and browser detection can get us out of a pinch and get things working how they should.

sometimes the situations leading up to us resorting to browser-detection are rage-inducing. But remember it’s often not the browser that is at fault. Even in the case of IE 6, it was the most standards-compliant and advanced browser of it’s time when it was released. And some of the standards that we have today were not complete at that time.

What should we do instead?
Real-world web design sometimes needs quick fixes, and making damn sure features work as intended. This doesn’t always allow for altruistic choices that leave out some functionality because it is the “right thing to do.”

Ideally
we would do capability testing. That’s the information we really need right? Test if the environment we are in is capable of what we want to do. If it is, do it.

-By
Nitin Uttarwar
Helical It Solution