JavaScript from Null: Utility Functions and Debugging
basixvideos

JavaScript from Null: Utility Functions and Debugging

Tutorial Details
  • Topic: JavaScript
  • Difficulty: Basix
  • Format: 24 Minute Video
This entry is part 7 of 7 in the series javascript-from-null

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!

Series Navigation«JavaScript from Null: Cross-Browser Event Binding

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://laroouse.com esranull

    very nice work thansk a lot

  • Yosy

    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

  • barry

    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();

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      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.

  • Dylan

    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;
    };

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      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.

      • Adam

        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” :).

  • barry

    @ dylan, you cant predefine the length of the new array because it is dynamic and will not update during the calculation. so thats good.

  • http://mixmo-anime.blogspot.com kankaro

    very nice JavaScript tuts… thanks a lot jeffrey… and for those who commments… thanks a lot for sharing ideas … :D

  • Nadeem

    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 ?

  • Marcin

    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

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      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.

      • Marcin

        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.

  • http://ufomuffin.com Alexa

    Nice, this website has gotten to a very good level. BTW Heard your interview at Jquery podcast very inspiring thx!

  • http://cmstutorials.org krike

    Nice tutorial :D but why is this posted in html & css ?

  • Mike Hopley

    The video doesn’t load for me — I just get the “loading spinner”.

    Tried on Chrome & FF.

    • piratelv

      Same with me.

      • http://www.jeffrey-way.com Jeffrey Way
        Author

        Just added an alternate link under the video for those who can’t see the video for some reason.

  • tarek

    thank you jeffrey ……

  • Daniel

    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/

  • Barry

    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.

    • John

      @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 ;-)

  • Barry

    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.

    • John

      Ha neat precision! Thx!

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Right – but (correct me if I’m wrong) IE7 and below don’t support the indexOf() method on the Array object.

      • Daniel

        oh, I see…

        thanks for the clarification all you guys!

  • Mike Hopley

    It’s working for me now.

    Excellent video, Jeffrey. :) I learned some new stuff.

  • Patrick

    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

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Good idea! We might just do that.

  • http://jportal.pl shpyo

    Like Marcin mentioned, better would be if you just extend Array object by prototype.
    Array.prototype.unique = function() {
    //your code
    }
    Cheers

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Maybe – but I didn’t think that was appropriate for a beginner tutorial. Extending native objects requires a full tutorial, itself.

  • Umair

    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

  • Myung Ki

    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….

    • ben

      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.

  • Ufuk

    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. ;)

  • Michel

    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?

  • Timothe Borel

    Hi jeff,

    Thanks to you, again, I know undestand a bit a javascript, i must admit it was 20 times more difficult than CSS.
    Though, your video tutorial is the only tut on the web that made me understand anything.

    I poped in here because I was following the free Jquery course and had no basis on javascript, hopefully now I do and will go on with the jquery video lessons.

    THANKS JEFF, you’re the man !!!

  • Mario

    watched the whole series! excellent work as usual. thanks again!