JavaScript from Null: Utility Functions and Debugging
Tutorial Details
- Topic: JavaScript
- Difficulty: Basix
- Format: 24 Minute Video
The Full Series
JavaScript University continues as we develop our first utility function that will allow us to filter and retrieve only the unique values from an array. Along the way, I’ll also teach you how to use the excellent Firebug to debug your code.
Utility Functions and Debugging
Final Code from the Video:
var unique = function(origArr) {
var newArr = [],
origLen = origArr.length,
found,
x, y;
for ( x = 0; x < origLen; x++ ) {
found = undefined;
for ( y = 0; y < newArr.length; y++ ) {
if ( origArr[x] === newArr[y] ) {
found = true;
break;
}
}
if ( !found) newArr.push( origArr[x] );
}
return newArr;
};
// Test it out
var myarray = ['jeffrey', 'allie', 'patty', 'damon', 'zach', 'jeffrey', 'allie'];
myarray = unique(myarray);
console.log(myarray); // jeffrey, allie, patty, damon, zach
Conclusion
So, with this lesson out of the way, you now know how to build your own helpful utility functions. I hope you enjoyed today's video tutorial!

very nice work thansk a lot
Hi Jefrrey,
You can use indexOf on array , the improved for loop code will be –
for ( x = 0; x returns the item index on arrA,If the item isn`t in arrA it will return -1.
Yosy
I don`t know but my message was cut off -
http://pastebin.com/YF05Au01
yeah i agree, it’s works also with the indexOf :)
in the code example on this site you are not defining y (x; y;) as a new var but as a global var in the window object wich is not good.
You can define them outside the for as 0 (x = 0, y = 0;) and in my opinion its better to use it at as a prototype.
array.unique();
Hi Barry –
The semicolon is just a typo. I’ve fixed it.
Ahh… extending the array object – I decided that it was best not to encourage that technique to beginners.
Couple notes, which I hesitate to mention, but will in the spirit of learning:
1) After declaring “x”, you should have a comma, not a semi colon.
2) You should set the length of the new array to a variable inside the first for() loop, so you don’t need to calculate the length of the new array on each iteration of the new array:
for (x = 0; x < origLen; x++ ) {
found = undefined;
newLen = newArr.length;
for (y = 0; y < newLen; y++ ) {
3) Since the declaration of unique() is a statement, it should be ended with a semi-colon.
4) For arrays of STRINGS ONLY, the function below works as well. It uses an object to store the values, so you don’t need to loop through the array n-squared times:
var unique = function(origArr) {
var newArr = [],
newVals = {},
origLen = origArr.length,
x;
for (x = 0; x < origLen; x++ ) {
if(newVals[origArr[x]] == undefined)
newArr.push(origArr[x]);
newVals[origArr[x]] = true;
}
return newArr;
};
Hey Dylan,
1) Yep; was a typo. Fixed.
2) You can’t “cache” the new array’s length, because it’ll potentially change with each loop.
Isn’t it going to change only after all inner loop iterations are done? In these inner-loop-iterations length is constant until actually something is added to the new array, but then the loop “breaks” :).
@ dylan, you cant predefine the length of the new array because it is dynamic and will not update during the calculation. so thats good.
very nice JavaScript tuts… thanks a lot jeffrey… and for those who commments… thanks a lot for sharing ideas … :D
request not on this topic ,
can you upload your vimrc and all the plug ins you are using into one package , in short your vim configuration folder :) , and whats the color-scheme name you are using ?
Here’s my Vimrc file: https://github.com/JeffreyWay/Vim/blob/master/vimrc
The color theme is: kellys
I’ve found another implementation which seems more elegant to me, as it does not require constant length checks in the internal loop. I’ve not done any performance test, but I guess it would be more performant on large arrays. Here it is: http://www.jslab.dk/library/Array.unique
Hey Marcin – I didn’t want to go into extending native objects this early in the series. Doing so requires a lot of explanation/warning.
Hey Jeff,
I was not referring to extending native objects. The method from my link could easily be changed into a helper function just like yours, but without the length check in the internal loop, so it should be a bit faster.
Nice, this website has gotten to a very good level. BTW Heard your interview at Jquery podcast very inspiring thx!
Nice tutorial :D but why is this posted in html & css ?
The video doesn’t load for me — I just get the “loading spinner”.
Tried on Chrome & FF.
Same with me.
Just added an alternate link under the video for those who can’t see the video for some reason.
thank you jeffrey ……
Thank you very much Jeffrey!
The “debugger” keyword was new to me and it seems very useful!
What about using the indexOf method? Is it reliable, performant? I think the code becomes a bit simpler :) example here: http://jsfiddle.net/t4v3B/
IndexOf is a method you can apply at strings, you can compage strings inside an array, but not other types like arrays, objects, functions etc…
If your array contains strings its fine, other then that avoid it for complete usage.
@Barry : From my testing (seen here: http://jsbin.com/ilave5/edit) it seems you’re wrong. Correct me if i’m mistaken.
@Jeffrey: I’ve been following you for a while. First time I have the opportunity to say thanks. Done ;-)
In my previous comment i said that indexOf can only applied to strings, back in the days that was true, but these days in modern browsers you can use Array.indexOf() and for older browsers you can prototype the same behavior into the Array object. So yes, you can use Array.indexOf() but think on support for older browsers.
Ha neat precision! Thx!
Right – but (correct me if I’m wrong) IE7 and below don’t support the indexOf() method on the Array object.
oh, I see…
thanks for the clarification all you guys!
It’s working for me now.
Excellent video, Jeffrey. :) I learned some new stuff.
Jeff,
This was an excellent tutorial. Can I suggest that NetTuts create a series of debugging screencast? Preferably using Firebug or, even Chromes debugger… This is an area that is lacking in exposure and needs much needed attention.
-Patrick
Good idea! We might just do that.
Like Marcin mentioned, better would be if you just extend Array object by prototype.
Array.prototype.unique = function() {
//your code
}
Cheers
Maybe – but I didn’t think that was appropriate for a beginner tutorial. Extending native objects requires a full tutorial, itself.
Jeff,
I think we can achieve this by putting value of an array as a key.
var unique = function(origArr) {
var newArr = [],
origLen = origArr.length,
x;
for ( x = 0; x < origLen; x++ ) {
newArr[origArr[x]] = origArr[x];
}
return newArr;
};
// Test it out
var myarray = ['jeffrey', 'allie', 'patty', 'damon', 'zach', 'jeffrey', 'allie'];
myarray = unique(myarray);
console.log(myarray); // jeffrey, allie, patty, damon, zach
Hey Jeffrey…
I wanna start by saying – THANX – thank you for all your great posts on development, they’ve helped me alot on designing and developing website content…. So Thank You…
I’ve got a Question for you – That i’ve been thinking about for a period…. And I hope that you’ll help me out….
Pleeeeaaase….
What to do ??? – I’m having a site with all of its content, everything is good and well…
and I have targeted a normal desctop monitor, and ipad…. Nice Nice….
Included a reference to jwuery on google api…… But i want to use 2 different customized js files. Because i want to us one js file for the interaction, on the monitor. And 1 js file for interaction on iPad…
How do I go about this one ?????????
In Advance – Thank You…. Hope to see some kind of feedback to this dillema….
I had this problem a while back and it drove me nuts!
In the end, you can get round it by using an if statement targeted towards the ipad or iphone as such –
if (navigator.platform == ‘iPad’ || navigator.platform == ‘iPhone’ || navigator.platform == ‘iPod’)
{
// ipad specific script goes here
} else {
// usual script goes here
}
I think that would work fix your problem, however I am a beginner aswell so I would be interested to hear a more efficient solution.
Hello Jeff,
thanks for all the great tutorials. Everything sounds so much easier when its explained by you. :) I have two questions:
1) Is this one the last one of the series or can we expect more in the near future?
2) Once you get the hang of JavaScript basics which are covered in this series, where to continue to work on real world examples like “challenging” navigation menus or other web applications? Most tutorials I find on the net have rather optimized code where its hard for a beginner to understand all the “short cuts” and “best practices”.
In the mean while, I will continue searching on netttuts seeing I’m only on page 4 of 19 under JavaScript & AJAX. ;)
He Jeffrey,
Thanks for the tuts ! I’ve enjoyed watching them.
Are you going to go further on this some day? and same questions as Ufuk: Where do you reccomend we should go from here?