employer cover photo
employer logo

IHS Markit Interview Question

How do you traverse an array in JavaScript?

Interview Answer

Anonymous

Jun 1, 2010

Arrays in JavaScript are declared as objects. var c = new Array( 5 ); Allocates 5 spaces in memory and returns the address of the first space to the variable c. This address cannot be extrapolated because pointers are not specifically implimented within JavaScript, although c is technically a pointer, as are all variables. c = [1, 5, 4, 77, 3]; Assigns the array 1, 5, 4, 77, 3 to the array within c. If we want to traverse the array we need only do the following: var j; for (j = 0; j < c.length; ++j) { c[j]; } Arrays have a length attribute which is public. If we want to output an array we do not need to traverse the array. document.writeln(c);