Monday, February 15, 2010

Array functions in javascript

Finally my first post of the year. Coding in core javascript scared me from the beginning because it does not have a perfect IDE with intellisense as java for eclipse. Coming to the point, I decided to improve myself in javascript. I was actually going through the arrays in javascript and read about some interesting functions. So decided to jot them down for my reference later. I am not sure how popular or how efficient these functions are. Most of my work's application is developed in javascript and I dont remember seeing any of these functions.

Lets consider we created an array      

  var array = ['kolli','ravi'];

Coming to the functions:

1) Push and pop: These are the simple functions that we all know since our undergrad mostly in data structures, stacks. So in an array push adds an element to the end of the array and pop deletes an element from the end of the array.



This statement adds ‘kanth’ to the end of the array now the array being [‘kolli’,’ravi’,’kanth’]


This statement removes the last element in the array resulting in [‘kolli’,‘ravi’]

2) unshift and shift: These functions are also used to insert and remove elements from the array but from the other end (beginning of the array).



This statement adds ‘Hye’ to the beginning of the array resulting in [‘hye’,’kolli’,’ravi’]


This statement removes the first element in the array. Result: [‘kolli’,’ravi’']

3) Splice: This is a little more complex function than the others. It can be used to add, remove, replace elements in the array.


splice(StartingPos, NoofItemsToDelete, Items_to_add);



This statement is going to insert ‘kanth’ at location 2 of the array, without deleting anything.


This statement is going to remove 1 element starting from position 2.


This statement is going to replace the element in position 1 resulting in array [‘kolli’,’rocks’].

Finally one more advantage of this function is that it lets us add more than one element to the array by just separating them with a ‘,’.

1 comment:

Sajjan Sarkar said...

Nice one again...! Not many people know abt push,join etc.. one of its biggest uses is while creating large strings by concatenating smaller strings..typical scenarios are while trying to create HTML content using javascript and rendering them using innerHTML (which,imho is not a good way at all, you'd rather just use the DOM methods which are elegant and structured)..rather than saying :
var str = "<input";
str+=" type='text'";
str+=... etc etc
You'd rather say:
var str = new Array();
OR you could use a StringBuilder class (which really just does the same thing,but provides easier handles) like the one at href=''..Overall this provides much faster code and is much more memory optimized..Nice article again Mr K.. keep em comin!