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

Add Comment

Discussion 39 Comments

  1. esranull says:

    very nice work thansk a lot

  2. Yosy says:

    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

  3. barry says:

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

    • Jeffrey Way says:
      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.

  4. Dylan says:

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

    • Jeffrey Way says:
      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 says:

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

  5. barry says:

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

  6. kankaro says:

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

  7. Nadeem says:

    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 ?

  8. Marcin says:

    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

    • Jeffrey Way says:
      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 says:

        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.

  9. Alexa says:

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

  10. krike says:

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

  11. Mike Hopley says:

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

    Tried on Chrome & FF.

  12. tarek says:

    thank you jeffrey ……

  13. Daniel says:

    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/

  14. Barry says:

    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.

  15. Barry says:

    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.

  16. Mike Hopley says:

    It’s working for me now.

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

  17. Patrick says:

    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

  18. shpyo says:

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

  19. Umair says:

    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

  20. Myung Ki says:

    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 says:

      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.

  21. Ufuk says:

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

  22. Michel says:

    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?

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.