Tutorial: How To Sort An Array In JavaScript

In JavaScript, we are given a method Sort() to perform sorting. Although Sort() is said to be used for sorting an array, it can also be used to sort anything other than an array itself. In this article we will discuss all about JavaScript array.

Sort() in JavaScript

By default, the method Sort() in JavaScript takes a given array and sort it in lexicographical order and not alphabetical order! This means that the Sort() method sort a given array in dictionary order. Let's consider the following example of Sort method.

var list =["Zebra", "Monkey", "Donkey"]
list.sort() //["Donkey", "Monkey", "Zebra"]

The above look fine when sorting an array of string but when it comes to number we will face a little problem.

var list =[ 39, 108, 21, 55, 18, 9]
list.sort() //[108, 18, 21, 39, 55, 9]

Looking at the result of the sort function seems to be unsorted but the fact that it is sorted according to lexicographical order does makes it in an ordered form after using the default sort method. Lucky, JavaScript doesn't force you to follow lexicographic order. You may also define a function to sort them in your own way.

Reverse Sort()

We get our result in lexicographical order after we performed a Sort() function. What if we want the reverse order of the sort function instead? In JavaScript, there is a function Reverse() which can help us to reverse the result of the array in the opposite order of the result. Consider the following example to illustrate Reverse() method in JavaScript.

var list =["Zebra", "Monkey", "Donkey"]
list.sort() //["Donkey", "Monkey", "Zebra"]
list.reverse() //["Monkey", "Zebra", "Donkey"]

Simple and powerful.

Customize Sort

The default Sort() function in JavaScript is quite simple and clear. Now, we will look at how we can customize this sort function. JavaScript Sort function does take in a parameter which is a function. Short to say, Sort() Method will sort your array instructed in the given function. However, the return value of the function must be as follow,

  • returns a value less than 0: parameter 'a' value is less than parameter 'b' value. 'a' come BEFORE 'b'.
  • returns a value greater than 0: parameter 'a' value is more than parameter 'b' value. 'a' come AFTER 'b'
  • returns exactly 0: parameter 'a' and 'b' have the same value. no change.

With the above rule, we can create a function that sort our array in numerical order instead of lexicographic order.

function sortmyway(data_A, data_B)
{
	if ( data_A < data_B ) // data_A come before data_B
		return -1;
	if ( data_A > data_B ) // data_A come After data_B
		return 1;
	return 0; // data_A == data_B, no change.

}
var list =[ 39, 108, 21, 55, 18, 9]
list.sort(sortmyway) // [9, 18, 21, 39, 55, 108]

The above example look good but the function seems to be a bit lengthy. You can change the comparison statement in a shorter form using the '?' symbol and we will get a shorter version of the code above.

function sortmyway(data_A, data_B)
{
return ((data_A < data_B) ? -1 : ((data_A > data_B) ? 1 : 0));
}
var list =[ 39, 108, 21, 55, 18, 9]
list.sort(sortmyway) // [9, 18, 21, 39, 55, 108]

We can even shorten the above declaration to perform the same task as shown below,

function sortmyway(data_A, data_B)
{
	return (data_A - data_B);
}
var list =[ 39, 108, 21, 55, 18, 9]
list.sort(sortmyway) //[9, 18, 21, 39, 55, 108]

All the methods above sort the array in ascending order.

Sort Descending order

Using the shortest method i have above, i can declare a sorting function which sort in descending order as follow,

function sortmyway(data_A, data_B)
{
	return (data_B - data_A);
}
var list =[ 39, 108, 21, 55, 18, 9]
list.sort(sortmyway) //[108, 55, 39, 21, 18, 9]

You can also achieve this by using the Reverse() method to eliminate the need to declare two sort function for ascending and descending order.

Random Sort Array

Well, we can also take advantage of the sort function to randomize our array. This way, we do not have to perform any loop which also contribute to function efficiency.

function sortmyway(data_A, data_B)
{
	return 0.5 - Math.random(); //random gives us result between 0 and 1
}
var list =[ 39, 108, 21, 55, 18, 9]
list.sort(sortmyway) //[21, 9, 39, 108, 18, 55]

Summary

Other than array, we can also sort unordered and ordered list. Sort() method in JavaScript can help us perform different kind of sorting in every type of element not restricting to array only. However, using JavaScript to perform sort of other element other than array can be a lot of pain. Personal advice is to use JavaScript framework such as jQuery or Mootools to ease the job. On the other hand, Sort() method can also be used to substitute unnecessary loop to create a more efficient code especially when comparing each element in an array is required. (we just have to eliminate the return value to perform such task) . Even eliminating duplication in an array is possible with Sort() method!

The Secret Arguments Array in JavaScript

Well, this is not really a secret to be exact. Many experience programmers who have worked with JavaScript for many years will surely come across arguments array. Some book may even forgotten the existence of arguments array since it is not widely used. Hence, i believe majority of JavaScript programmers do not actually know the existence of such array in JavaScript. So allow me to explain what is arguments array.

Arguments Array

An arguments array is a predefined array used within a function in JavaScript. Whether you used it or not it will still exist within that function. The main advantage of using arguments array is the unlimited number of argument or parameter you can pass into a function. Let's consider the following example,

function example()
{
	var sum = 0;
	for(i = 0; i < arguments.length;i++)
	{
		sum += arguments[i];
	}
	alert(sum); //45
}
example(1,2,3,4,5,6,7,8,9,0);

i find that the above example will simply get the idea through how arguments array worked. It is an array so whatever we passed in via arguments will be placed into an arguments array within the function. Then, we simple just used it. The above example is an simple addition function. You can see another example at override ‘this’ object in JavaScript

Detect Arguments

What if we want to use the arguments array in certain circumstances but not all the times? Preload with jQuery shows one particular function that uses an array or parameter depend on how users want to use that function (now, you might have guess how a library such as jQuery allows multiple different parameter for a single function). In order to do that, we have to detect what arguments or values been passed on to the function.

In JavaScript, we can detect a particular value by using comparison operators (===, ==, !=, etc.) but there are also other techniques to detect these arguments. We can use in operator which detect whether a given value is in the arguments array (in operator is not widely supported. Thus, you don't see many using it). There are also typeOf operator which determine what is the type of the value (string, object, int, etc.)which you can see from Preload with jQuery article. Lastly, there is Autocasting operator which evaluate whether a variable has a value (NaN, 0, false, undefined, null, or an empty string are considered as no value). Let's look at each new detection method example that i mention here.

//Detect whether there is a "hello" member in the arguments array: 
var parameter = 'hello' in arguments? arguments : "";

//Detect whether arguments contains at least one argument
var parameter = typeof arguments[0] != 'undefined'? arguments : "";

//Detect whether the user passed an object(can be array) or a list of arguments
var parameter = (typeof arguments[0] == 'object')? arguments[0] : arguments;

//Detect whether there is an arguments passed into the function and assign the number of arguments into the variable
var parameter = arguments.length || "";

Summary

Using Argument Array is great as we are not restricted by the number of parameter on a given function. However, many online tutorial on basic JavaScript no longer practice this since it is said that this has been depreciated with new browsers emerged but its still usable in JavaScript up till today (who said its depreciated!).

Tutorial: How to override ‘this’ object in JavaScript

Have you ever experience a time when the calling object 'this' needed to be override and somehow you just couldn't do that? You tried left hand assignment but it just won't work? wondering how can 'this' object be overridden in JavaScript but can't find the correct answer on Google? This article will explain how this can be done.

Left hand assignment

Ever tried left hand assignment to override 'this' object?

var obj = document.getElementById("button");
this = obj

It will fail and gives you 'invalid assignment left-hand side'.

Using Call() to override 'this' object

There is a function in JavaScript, Call() which can help you override 'this' object or specify the 'this' object. Let's consider the following example,

function example(a,b)
{
	this.value == 'button'?alert(a):alert(b);
}
var textobj = document.getElementById('input_relink');
example.call(textobj, 'It is a button!', 'It is not a button');

We look at a text box and check whether the user key in 'button'. But we uses 'this' object to verify the input text in the function example which takes in two parameter as shown above. The Call() method is used whenever you wish to override 'this' object which is placed at the first parameter and the rest of the parameter will be exactly the same as the method parameter. Hence, we used the function in this way for the above example because it has two parameter.

//override 'this' with object 'textobj'
example.call(textobj, 'It is a button!', 'It is not a button');

If we have another function which takes in 3 parameter, we will do this.

function example(a,b, c)
{
	this.value == 'button'?alert(a):alert(b);
	alert(c);
}
var textobj = document.getElementById('input_relink');
example.call(textobj, 'It is a button!', 'It is not a button', 'Completed');

You can also used it without parameter like the one illustrated below,

var o = { x: 15 };
function f()
{
    alert(this.x);
}
f.call(o);

Using Call() method restrict your variable given on the method. On the other hand, we can use another method Apply() which override the 'this' object giving the second parameter as an array.

Using Apply() method to override 'this' object

The difference between call and apply method is the parameter needed to use them. For Call() method it depends on the parameter of the function as shown above. But for Apply() method it can have more than the amount of parameter in the function (since it takes in an array). Similarly, the first parameter of both methods are used to override 'this' object. Let's consider the following example,

var o = { x: 8 };
function example()
{          
    // arguments[0] == object 
	var sum = 0;
    for(var i = 1; i < arguments.length; i++)
    {
       sum+=arguments[i]
    }
	alert(sum+ this.x);
}
example.apply(o, 1, 2, 3, 4)

I am using the depreciated argument array to look through the argument being passed into the function, sum them up, alert to the user. Similarly, i can do this using an array.

var o = { x: 8 };
function example(a, b, c)
{          
	alert(this.x+a+b+c);
}
example.apply(o, [1,2,3])

Pretty simple isn't it?

Tutorial: Function within a function in JavaScript

Do you know that you can define a function within a function in JavaScript? Furthermore, these functions defined in the outer function are not accessible outside the scope unless you expose them to the outside scope? This is pretty interesting since basic web tutorial doesn't really cover function in a function with JavaScript. Function in a function are only noticeable when you come across or read about in the real world of JavaScript application.

Function within a function

How do you define a function within a function in JavaScript? Pretty simple and straight forward actually. Just throw another function into the function. This will caused the inner function to be accessible only within the scope of outer function.

function outer_func(){
	function inner_func(){
		alert('hellow');
	}
	//hellow will be alert
	inner_func();
}

If you try to access the inner function, an undefined error will occurs. On the other hand, using the outer function still permits.

//undefined function
inner_func();
//alert 'hellow'
outer_func();

Access the inner functions

Sometimes we want some methods in the outer function to be accessible. We will have to return an object with the relevant method attached to it for it to be accessible outside the scope.

function outer_func(){
	var newObj = new Object() 
	function inner_func(){
		alert('hellow');
	}
	function inner_func2(){
		alert('RAWR!');
	}
	newObj.inner_func = inner_func;
	return newObj;
}

Above, we created two function and only attached the first function into the return object. Thus, calling the second function will fail.

var func_Obj = new outer_func();
// alert 'hellow'
func_Obj.inner_func();
//undefined
func_Obj.inner_func2();

Some Real World Application

Function within a function act as a security measure for certain action to be restricted outside the scope. Open source code tend to use this to prevent certain dependency methods from being access. Performing certain organization through this method was also applied in real life application.

Understanding Preloading For Web Components

We heard preloading almost every time! But do you really understand what is preloading and how does preloading actually work? In this article, we will talk about preloading and how it should and can be use.

What is Preloading

Most of us will know but there are many that are unclear. Preloading is an action that will load components which are not visible available to the users. This means that any component that are already in the HTML document will be loaded and preloading doesn't help speeding up these components. What we would like to preload are those components that do not resist within the document and components for future pages.

Why Preload component

Why do we want to preload a component if it doesn't help speeding up the existing components on the HTML document?! Simple, let's say we have a gallery which has the following code in our document

<img src='example.jpg'/>

compare to document that has these codes

<img src='example.jpg'/>
<img src='example1.jpg'/>
<img src='example2.jpg'/>
<img src='example3.jpg'/>
<img src='example4.jpg'/>
<img src='example5.jpg'/>
<img src='example6.jpg'/>

Assuming each image in these example are 800kb in size (If you have a script that wait for an onload event to occurs, i wonder when will the script start running). It will be obvious which one will finish first (the first example). So your user gets to see the result like less than 1 minute. The sub sequence images will be preload into the document while the user is still viewing the first one. Thus, clicking the next button will show a loading in progress or immediately displayed the second image depending on how you construct your script to accomplish this.

Although we didn't speed up the image loading time but we manage to speed up the overall waiting time for the whole page to be display completely. Thus, preloading allows us to practice 'load only when needed' concept. This means that those that are not going to display first should be loaded last and allow the page to be fully loaded before their turn is up to run.

If you have very big file size page, it will serve as a notification to the users that the site is loading. On the other hand, preloading allows you to cache them onto the user browser for better responsiveness. (although there are disadvantages of doing this too) This way, sub sequence pages will have better 'speed'.

What component can be preloaded?

Basically you will want these components to be preloaded first since they usually take up the most loading time.

  • Images files
  • Flash files
  • Sound files

There are not much reason to preload other type of document unless they are very big in size. Most document are small enough to load within a few seconds but the one mention above are usually the one we are concern with during web development.

What are the methods for preloading

This depend on which components are you trying to preload. There are all sort of ways to preload certain components such as JavaScript, ActionScript, CSS, Ajax or HTML tag. So depend on which one are you trying to preload and what are you trying to accomplish. Flash files will most likely be ActionScript. For Images, people tend to use CSS, JavaScript for caching and Ajax for preloading with loading image. While sound files will be using embed tag.

How Preloading work

In a way, preloading can be describe as work behind the scene. Basically, the user will not be able to notice. But different way of preloading work differently,

CSS

In CSS, the objective is to hide those component you want to preload. And you might want it to be placed at the last row in your HTML document (means it will load only all relevant component has loaded). Methods used are usually,

  1. Visibility: hidden
  2. display: none
  3. width:0px;height:0px;
  4. top: -99999px; or left: -999999px

The objective is to hide it so that it will store in the cache.

JavaScript

In JavaScript, we used the image object. (this method can also be used to preload flash files into the cache)

var obj = new Image();
obj.src = 'test.jpg';

This way it will preload the images for sub sequence pages as the images are cached. This method can also be used to produce loading image before applying the following code

document.getElementById('container').innerHTML = '<img src='test.jpg/>';

Ajax

Ajax let the server script to load the image page, cached and send it back to the document for display.

function preload(url) {
  // display loading image
  // send the url to be open on the server side. hence, cached.
  document.getElementById('loading').style.visibility = 'visible';
  document.getElementById('container').innerHTML = '';
  var obj =  new XMLHttpRequest();
  obj.open('GET', url, true);

  obj.onreadystatechange = function() {		
    if (obj.readyState == 4 && obj.status == 200) {
      // once cached, we hide the loading image and display the content
      if (obj.responseText) {
        document.getElementById('container').innerHTML = '<img src=''+url+''/>';
        document.getElementById('loading').style.visibility = 'hidden';
      }
    }
  };
  obj.send(null);
}

During the request, we can display a loading in progress image until the new image has loaded. However, this doesn't seems to work on IE 7. (this is shown later on demo section)

HTML tag

This is usually used for sound files.

<EMBED NAME='mySound' SRC='mySound.mid' 
LOOP=FALSE AUTOSTART=FALSE HIDDEN=TRUE MASTERSOUND>

Action Script

If you are interested, here is a video.

The Demonstration

i will demonstrate using Ajax which the code has been written above. Please click the image to see the loading. Here are the files and demo