Seven JavaScript Things I Wish I Knew Much Earlier In My Career

Advertisement

I’ve been writing JavaScript code for much longer than I care to remember. I am very excited about the language’s recent success; it’s good to be a part of that success story. I’ve written dozens of articles, book chapters and one full book on the matter, and yet I keep finding new things. Here are some of the “aha!” moments I’ve had in the past, which you can try out rather than waiting for them to come to you by chance.

Shortcut Notations

One of the things I love most about JavaScript now is shortcut notations to generate objects and arrays. So, in the past when we wanted to create an object, we wrote:

var car = new Object();
car.colour = 'red';
car.wheels = 4;
car.hubcaps = 'spinning';
car.age = 4;

The same can be achieved with:

var car = {
  colour:'red',
  wheels:4,
  hubcaps:'spinning',
  age:4
}

Much shorter, and you don’t need to repeat the name of the object. Right now, car is fine, but what happens when you use invalidUserInSession? The main gotcha in this notation is IE. Never ever leave a trailing comma before the closing curly brace or you’ll be in trouble.

The other handy shortcut notation is for arrays. The old school way of defining arrays was this:

var moviesThatNeedBetterWriters = new Array(
  'Transformers','Transformers2','Avatar','Indiana Jones 4'
);

The shorter version of this is:

var moviesThatNeedBetterWriters = [
  'Transformers','Transformers2','Avatar','Indiana Jones 4'
];

The other thing about arrays is that there is no such thing as an associative array. You will find a lot of code examples that define the above car example like so:

var car = new Array();
car['colour'] = 'red';
car['wheels'] = 4;
car['hubcaps'] = 'spinning';
car['age'] = 4;

This is not Sparta; this is madness—don’t bother with this. “Associative arrays” is a confusing name for objects.

Another very cool shortcut notation is the ternary notation for conditions. So, instead of the following…

var direction;
if(x < 200){
   direction = 1;
 } else {
   direction = -1;
 }

… You could write a shorter version using the ternary notation:

var direction = x < 200 ? 1 : -1;

The true case of the condition is after the question mark, and the other case follows the colon.

JSON As A Data Format

Before I discovered JSON to store data, I did all kinds of crazy things to put content in a JavaScript-ready format: arrays, strings with control characters to split, and other abominations. The creation of JSON1 by Douglas Crockford changed all that. Using JSON, you can store complex data in a format that is native to JavaScript and doesn't need any extra conversion to be used immediately.

JSON is short for "JavaScript Object Notation" and uses both of the shortcuts we covered earlier.

So, if I wanted to describe a band, for example, I could do the following:

var band = {
  "name":"The Red Hot Chili Peppers",
  "members":[
    {
      "name":"Anthony Kiedis",
      "role":"lead vocals"
    },
    {
      "name":"Michael 'Flea' Balzary",
      "role":"bass guitar, trumpet, backing vocals"
    }, 
    {
      "name":"Chad Smith",
      "role":"drums,percussion"
    },
    {
      "name":"John Frusciante",
      "role":"Lead Guitar"
    }
  ],
  "year":"2009"
}

You can use JSON directly in JavaScript and, when wrapped in a function call, even as a return format of APIs. This is called JSON-P and is supported by a lot of APIs out there. You can use a data endpoint, returning JSON-P directly in a script node:

<div id="delicious"></div><script>
function delicious(o){
  var out = '<ul>';
  for(var i=0;i<o.length;i++){
    out += '<li><a href="' + o[i].u + '">' + 
           o[i].d + '</a></li>';
  }
  out += '</ul>';
  document.getElementById('delicious').innerHTML = out;
}
</script>
<script src="http://feeds.delicious.com/v2/json/codepo8/javascript?count=15&callback=delicious"></script>

This calls the Delicious Web service to get my latest JavaScript bookmarks in JSON format and then displays them as an unordered list.

In essence, JSON is probably the most lightweight way of describing complex data—and it runs in a browser. You can even use it in PHP using the json_decode() function.

Native JavaScript Functions (Math, Array And String)

One thing that amazed me is how much easier my life got once I read up thoroughly on the math and string functions of JavaScript. You can use these to avoid a lot of looping and conditions. For example, when I had the task of finding the largest number in an array of numbers, I used to write a loop, like so:

var numbers = [3,342,23,22,124];
var max = 0;
for(var i=0;i<numbers.length;i++){
  if(numbers[i] > max){
    max = numbers[i];
  }
}
alert(max);

This can be achieved without a loop:

var numbers = [3,342,23,22,124];
numbers.sort(function(a,b){return b - a});
alert(numbers[0]);

Notice that you cannot use sort() on a number array because it sorts lexically. There's a good tutorial on sort() here2 in case you need to know more.

Another interesting method is Math.max(). This one returns the largest number from a list of parameters:

Math.max(12,123,3,2,433,4); // returns 433

Because this tests for numbers and returns the largest one, you can use it to test for browser support of certain properties:

var scrollTop= Math.max(
 doc.documentElement.scrollTop,
 doc.body.scrollTop
);

This works around an Internet Explorer problem. You can read out the scrollTop of the current document, but depending on the DOCTYPE of the document, one or the other property is assigned the value. When you use Math.max() you get the right number because only one of the properties returns one; the other will be undefined. You can read more about shortening JavaScript with math functions here3.

Other very powerful functions to manipulate strings are split() and join(). Probably the most powerful example of this is writing a function to attach CSS classes to elements.

The thing is, when you add a class to a DOM element, you want to add it either as the first class or to already existing classes with a space in front of it. When you remove classes, you also need to remove the spaces (which was much more important in the past when some browsers failed to apply classes with trailing spaces).

So, the original function would be something like:

function addclass(elm,newclass){
  var c = elm.className;
  elm.className = (c === '') ? newclass : c+' '+newclass;
}

You can automate this using the split() and join() methods:

function addclass(elm,newclass){
  var classes = elm.className.split(' ');
  classes.push(newclass);
  elm.className = classes.join(' ');
}

This automatically ensures that classes are space-separated and that yours gets tacked on at the end.

Event Delegation

Events make Web apps work. I love events, especially custom events, which make your products extensible without your needing to touch the core code. The main problem (and actually one of its strengths) is that events are removed from the HTML—you apply an event listener to a certain element and then it becomes active. Nothing in the HTML indicates that this is the case though. Take this abstraction issue (which is hard for beginners to wrap their heads around) and the fact that "browsers" such as IE6 have all kind of memory problems and too many events applied to them, and you'll see that not using too many event handlers in a document is wise.

This is where event delegation4 comes in. When an event happens on a certain element and on all the elements above it in the DOM hierarchy, you can simplify your event handling by using a single handler on a parent element, rather than using a lot of handlers.

What do I mean by that? Say you want a list of links, and you want to call a function rather than load the links. The HTML would be:

<h2>Great Web resources</h2>
<ul id="resources">
  <li><a href="http://opera.com/wsc">Opera Web Standards Curriculum</a></li>
  <li><a href="http://sitepoint.com">Sitepoint</a></li>
  <li><a href="http://alistapart.com">A List Apart</a></li>
  <li><a href="http://yuiblog.com">YUI Blog</a></li>
  <li><a href="http://blameitonthevoices.com">Blame it on the voices</a></li>
  <li><a href="http://oddlyspecific.com">Oddly specific</a></li>
</ul>

The normal way to apply event handlers here would be to loop through the links:

// Classic event handling example
(function(){
  var resources = document.getElementById('resources');
  var links = resources.getElementsByTagName('a');
  var all = links.length;
  for(var i=0;i<all;i++){
    // Attach a listener to each link
    links[i].addEventListener('click',handler,false);
  };
  function handler(e){
    var x = e.target; // Get the link that was clicked
    alert(x);
    e.preventDefault();
  };
})();

This could also be done with a single event handler:

(function(){
  var resources = document.getElementById('resources');
  resources.addEventListener('click',handler,false);
  function handler(e){
    var x = e.target; // get the link tha
    if(x.nodeName.toLowerCase() === 'a'){
      alert('Event delegation:' + x);
      e.preventDefault();
    }
  };
})();

Because the click happens on all the elements in the list, all you need to do is compare the nodeName to the right element that you want to react to the event.

Disclaimer: while both of the event examples above work in browsers, they fail in IE6. For IE6, you need to apply an event model other than the W3C one, and this is why we use libraries for these tricks.

The benefits of this approach are more than just being able to use a single event handler. Say, for example, you want to add more links dynamically to this list. With event delegation, there is no need to change anything; with simple event handling, you would have to reassign handlers and re-loop the list.

Anonymous Functions And The Module Pattern

One of the most annoying things about JavaScript is that it has no scope for variables. Any variable, function, array or object you define that is not inside another function is global, which means that other scripts on the same page can access—and will usually override— them.

The workaround is to encapsulate your variables in an anonymous function and call that function immediately after you define it. For example, the following definition would result in three global variables and two global functions:

var name = 'Chris';
var age = '34';
var status = 'single';
function createMember(){
  // [...]
}
function getMemberDetails(){
  // [...]
}

Any other script on the page that has a variable named status could cause trouble. If we wrap all of this in a name such as myApplication, then we work around that issue:

var myApplication = function(){
  var name = 'Chris';
  var age = '34';
  var status = 'single';
  function createMember(){
    // [...]
  }
  function getMemberDetails(){
    // [...]
  }
}();

This, however, doesn't do anything outside of that function. If this is what you need, then great. You may as well discard the name then:

(function(){
  var name = 'Chris';
  var age = '34';
  var status = 'single';
  function createMember(){
    // [...]
  }
  function getMemberDetails(){
    // [...]
  }
})();

If you need to make some of the things reachable to the outside, then you need to change this. In order to reach createMember() or getMemberDetails(), you need to return them to the outside world to make them properties of myApplication:

var myApplication = function(){
  var name = 'Chris';
  var age = '34';
  var status = 'single';
  return{
    createMember:function(){
      // [...]
    },
    getMemberDetails:function(){
      // [...]
    }
  }
}();
// myApplication.createMember() and 
// myApplication.getMemberDetails() now works.

This is called a module pattern or singleton. It was mentioned a lot by Douglas Crockford and is used very much in the Yahoo User Interface Library YUI5. What ails me about this is that I need to switch syntaxes to make functions or variables available to the outside world. Furthermore, if I want to call one method from another, I have to call it preceded by the myApplication name. So instead, I prefer simply to return pointers to the elements that I want to make public. This even allows me to shorten the names for outside use:

var myApplication = function(){
  var name = 'Chris';
  var age = '34';
  var status = 'single';
  function createMember(){
    // [...]
  }
  function getMemberDetails(){
    // [...]
  }
  return{
    create:createMember,
    get:getMemberDetails
  }
}();
//myApplication.get() and myApplication.create() now work.

I've called this "revealing module pattern6."

Allowing For Configuration

Whenever I've written JavaScript and given it to the world, people have changed it, usually when they wanted it to do things that it couldn't do out of the box—but also often because I made it too hard for people to change things.

The workaround is to add configuration objects to your scripts. I've written about JavaScript configuration objects in detail7, but here's the gist:

  • Have an object as part of your whole script called configuration.
  • In it, store all of the things that people will likely change when they use your script:
    • CSS ID and class names;
    • Strings (such as labels) for generated buttons;
    • Values such as "number of images being displayed," "dimensions of map";
    • Location, locale and language settings.
  • Return the object as a public property so that people can override it.

Most of the time you can do this as a last step in the coding process. I've put together an example in "Five things to do to a script before handing it over to the next developer8."

In essence, you want to make it easy for people to use your code and alter it to their needs. If you do that, you are much less likely to get confusing emails from people who complain about your scripts and refer to changes that someone else actually did.

Interacting With The Back End

One of the main things I learned from all my years with JavaScript is that it is a great language with which to make interactive interfaces, but when it comes to crunching numbers and accessing data sources, it can be daunting.

Originally, I learned JavaScript to replace Perl because I was sick of copying things to a cgi-bin folder in order to make it work. Later on, I learned that making a back-end language do the main data churning for me, instead of trying to do all in JavaScript, makes more sense with regard to security and language.

If I access a Web service, I could get JSON-P as the returned format and do a lot of data conversion on the client, but why should I when I have a server that has a richer way of converting data and that can return the data as JSON or HTML… and cache it for me to boot?

So, if you want to use AJAX, learn about HTTP and about writing your own caching and conversion proxy. You will save a lot of time and nerves in the long run.

Browser-Specific Code Is A Waste Of Time. Use Libraries!

When I started Web development, the battle between using document.all and using document.layers as the main way to access the document was still raging. I chose document.layers because I liked the idea of any layer being its own document (and I had written more than enough document.write solutions to last a lifetime). The layer model failed, but so did document.all. When Netscape 6 went all out supporting only the W3C DOM model, I loved it, but end users didn't care. End users just saw that this browser didn't show the majority of the Internets correctly (although it did)—the code we produced was what was wrong. We built short-sighted code that supported a state-of-the-art environment, and the funny thing about the state of the art is that it is constantly changing.

I've wasted quite some time learning the ins and outs of all of the browsers and working around their issues. Doing this back then secured my career and ensured that I had a great job. But we shouldn't have to go through this trial by fire any longer.

Libraries such as YUI, jQuery and Dojo are here to help us with this. They take on the problems of browsers by abstracting the pains of poor implementation, inconsistencies and flat-out bugs, and relieve us of the chore. Unless you want to beta test a certain browser because you're a big fan, don't fix browser issues in your JavaScript solutions, because you are unlikely to ever update the code to remove this fix. All you would be doing is adding to the already massive pile of outdated code on the Web.

That said, relying solely on libraries for your core skill is short-sighted. Read up on JavaScript, watch some good videos and tutorials on it, and understand the language. (Tip: closures are God's gift to the JavaScript developer.) Libraries will help you build things quickly, but if you assign a lot of events and effects and need to add a class to every HTML element in the document, then you are doing it wrong.

Resources

In addition to the resources mentioned in this article, also check out the following to learn more about JavaScript itself:

You may be interested in the following related posts:

(al)

Footnotes

  1. 1 http://json.org
  2. 2 http://www.javascriptkit.com/javatutors/arraysort.shtml
  3. 3 http://www.wait-till-i.com/2007/06/28/shortening-javascripts-with-math/
  4. 4 http://icant.co.uk/sandbox/eventdelegation/
  5. 5 http://developer.yahoo.com/yui
  6. 6 http://www.wait-till-i.com/2007/08/22/again-with-the-module-pattern-reveal-something-to-the-world/
  7. 7 http://www.wait-till-i.com/2008/05/23/script-configuration/
  8. 8 http://www.wait-till-i.com/2008/02/07/five-things-to-do-to-a-script-before-handing-it-over-to-the-next-developer/
  9. 9 http://yuiblog.com/crockford/
  10. 10 http://dev.opera.com/articles/wsc/
  11. 11 http://www.smashingmagazine.com/2010/02/22/the-seven-deadly-sins-of-javascript-implementation/
  12. 12 http://www.smashingmagazine.com/2010/02/10/some-things-you-should-know-about-ajax/
  13. 13 http://www.smashingmagazine.com/2010/01/12/45-powerful-css-javascript-techniques/

↑ Back to top Tweet itShare on Facebook

An international Developer Evangelist working for Mozilla in the lovely town of London, England.

Advertisement
  1. 1

    I think this is very useful article. We always must revisit our knowledge and certainly have a lot to learn.

    0
  2. 102

    I’m agree with you on some points.

    0
  3. 203

    Seconded! That was the first thing I noticed here. If your array is small, this use of sort may make sense (n * interpreted_code may be bigger than n * logn * compiled_code), but even a straightforward interpreter is likely to be no more than 50 times slower than the library sort, so for arrays that may be more than 2500 entries you’ll always be better off with a loop. If you’re using a JIT compiler, your interpreter overhead could be as low as 4 or 5 times, so stick to arrays less than 20 elements or so for the sort hack.

    0
  4. 304

    I started reading it, thinking it would be junk, and it turned it to be something I really needed with lots of little gold nuggets. Out-flippin-standing article. I copied it to my personal KB database for future reference.

    Thanks SM. Groovy beans.

    0
  5. 405

    I use javascript a lot in my website, I love this article, please keep posting.
    Thanks,

    0
  6. 506

    You noticed in your math example, that you have switched the complexity of your code from O(n) to O(n * log(n))?
    What do you think does your nifty sort function do?
    You have just substituted, your loop with a function, which not only have to loop over your data (once), but to sort it, which is much more complex than just finding the max value.

    0
  7. 607

    Great article, I am a huge supporter for Event delegation, though there is one downside to event delegation, is that it doesn’t work for every event, at least in IE 6 ;). For example if you create a container which has several select boxes, you listen to the container, but because onchange doesn’t bubble, you won’t be able to listen to it.

    Thanks for the article, I wish, it had made it into the smashing book ;)

    0
  8. 708

    A nice and useful article

    0
  9. 809

    Regardless of what some people above are saying, I found this article very useful! I definately wouldn’t call myself a JS expert, but I’m not exactly new either, and I found some of the built-in functions here, as well as the short hand notation very useful.

    Bring on more articles concerning programming Smashing! Love the articles, love the site, love the network.

    0
  10. 910

    Good artilce for a beginner like myself. I am as fresh (green) as they come right now and this was very helpful. One thing I wish I could find, and have not, is a “case study” for a semi-complicated script which walks through the script line by line. Everything I’m reading right now either assumes I know too much and leaves out details I don’t know yet, or is waaay too simple (“hello world”) and uses doument.write for every stinkin example. Just an idea on another way to help beginners, coming from a beginner.

    Thanks,
    D

    0
  11. 1011

    Hey Guys,

    I’ve been a graphic designer for a couple of years now, but have absolutely NO clue when it comes to coding. Is anyone willing to share a few resources for a beginner?

    Much appreciated,
    Ryan

    0
  12. 1112

    Great post for someone who’s new to Javascript!

    I’ve been coding javascript for a few years now and I didn’t know about some of the shorthand notations! So thanks for this!

    0
  13. 1213

    nice article!

    0
  14. 1314

    Arnoud ten Hoedt

    April 22, 2010 1:39 am

    I agree that this should not be the baseline to depend your html and CSS design and accessibility on. It is however an excellent solution for fixing the x-browser quirks and fine tuning visual issues you basically always run into.

    Having to check your CSS and JS with a new browser release is a non-argument, because you need to do regression testing anyhow. If it isn’t broken, however, then don’t fix it. You implement this to fix issues, nothing more, nothing less.

    0
  15. 1415

    Yes , i agree this is one of the rare articles available for intermediate learner of JavaScript . There are not much help on net to improve JavaScript programming skills from beginner to intermediate/ advance. Like as you said line by line explanation of code samples that shows problems solved and concepts(problem solving) used.

    This is very good post, disappointing to read such harsh comments from few people on this post.

    0
  16. 1516

    Htere is only one aswer. Because of headline: Seven JavaScript Things I Wish I Knew Much Earlier In My Career.
    It’s looking like something advanced, something cool, something interesting and after reading this article you know that autor didn’t learn basics at beginning (of his career). Is i cool, interesting or advanced? In my opinion: NO.

    -3
  17. 1617

    goog article!

    0
  18. 1718

    Hello Ryan,
    you should go to library. Read some books and you will learn a lot.

    Tom.

    0
  19. 1819

    Thanks a ton !!!!!!!!!!

    0
  20. 1920

    Amy Blankenship

    April 23, 2010 7:09 am

    “Much shorter, and you don’t need to repeat the name of the object. Right now, car is fine, but what happens when you use invalidUserInSession?”

    Wouldn’t this work as well?

    with (invalidUserInSession) {
    prop1=’foo';
    prop2=’bar';
    }

    I don’t believe your “singleton” pattern is any such thing–it doesn’t enforce a single instance of the variable. Instead, you’re taking advantage of ECMAScript method closures to pseudo encapsulate properties of an “object” that’s actually a function:

    http://jibbering.com/faq/faq_notes/closures.html

    HTH;

    Amy

    0
  21. 2021

    Roshan Bhattarai

    April 23, 2010 8:40 am

    XLS stop talking nonsense.

    2
  22. 2122

    Frusciante is not in Red Hot Chili Pepers anymore =P

    0
  23. 2223

    I wouldn’t lose any sleep of that comment, SM. A pat on one’s own back, thinly veiled as a bit of constructive criticism.

    0
  24. 2324

    yikes some of the commenters on here are making me cringe… you’ve gotta be a bit ‘socially challenged’ to log on and boast the article is beneath you in order to feel better about yourself…..

    after reading numerous authors/blogs/books over the last year to skill up on javascript, I think the author is one of the best. No ego surfing just common sense and good practise, clearly explained

    0
  25. 2425

    Smashing Magazine, there’s something pretty unclear to me. How come that some (ok, harshly) criticizing comments are promptly highlighted as “negative comments” but Myxomato calling people “retards” and…wait for it… “f***tards” is not considered (at least) “negative”? What if Myxomato would’ve called SM “f***tards”? Would you still stand by?

    Personally, I consider this JS related stuff a nice lecture, even if I’m a designer, not a developer. IMO, Smashing Magazine still is the first bookmark for good articles, but I cannot help myself observing the the horde of “yesmen” that keeps growing. God forbid, should you ever say anything else than “great!”, they’ll devour you. :)

    0
  26. 2526

    I really enjoyed this article and I would love to see more like it. You guys have a lot of great articles but this one is definitely the kind I’m most interested in. I’m a big fan I bought you book, your site is my home page, if the numbers don’t reflect this just yet I think it because you’ve developed more of a designer base than coders, a mixture of what you’re doing now coupled with “beginner”/advanced articles on open source development coverage, strategies, etc would keep me a fan for a very long time to come. In closing, how could I submit an article for publishing? Anything I could so to help your success would be the least I can do for all I’ve learned from you guys. Keep up the good work.
    -sm

    0
  27. 2627

    I prefer to use jQuery over javascript most of the times. But some tips can be used for jQ too.

    0
  28. 2728

    Despite all the negative criticism, I really liked this article. Although it did not contain any breaking news, it surely refreshed old knowledge. Keep it up Smashing!

    0
  29. 2829

    This article actually made me return to SM, cos I was under the impression that it had devolved into an inspiration list post site. I’m not a beginner to javascript, but since I’m more of a jack-of-all-trades, it was refreshing to learn some of the finer points of JS from the likes of respected minds like Christian’s.

    Ignore the naysayers. It’s great to see varied articles for a varied audience. You can’t please all the people all the time anyways.

    0
  30. 2930

    Nice
    Thanks very useful

    0
  31. 3031

    Jan Philipp Pietrzyk

    April 27, 2010 8:41 am

    Do you really often need to check for the current browser and Version? I have never used such hacks, in spite of the IE.

    The problem will be, that it is much to easy to just write for known and not for future browsers. I don’t know where the problem with feature detection is. jQuery does it, MooTools has $defined(), it is much safer to use these constructs, because you can not accidently close the door for a future version of the same browser (e.g. IE9 with the W3C-Event Model).

    0
  32. 3132

    My own feeling about these javascript techniques as described in this article, is that many of them are exactly what is wrong with the language and what is wrong with a lot of C++ generation coding in general. The extreme terseness of many of these methods makes the code much more difficult to read and edit by a team of developers or by future developers.

    Such terse, opaque coding is a great way to shore up your own long-term employment prospects since it is so difficult to make sense of the code. But I would submit that the “long way” is materially no less efficient for computers, and is equally or more efficient for groups of programmers who have to collaborate on coding projects. It does mean more typing, of course, but so much less difficulty troubleshooting!

    0
  33. 3233

    Thanks for this , very very useful. great articles throughout the whole site!

    0
  34. 3334

    This shortened code is much harder to read and it takes more time to understand it or edit.

    0
  35. 3435

    I have been coding JS since Brendan Eich was coding the first version (I used to talk to him regulary as well when I was writing my own books on Internet programming.)Shortening and optimising JavaScript to make it do essentially the same thing is useful, but it’s not the be-all and end-all of “web development”. Any techniques that work and are robust are fine. There’s nothing new here; I wrote about these techniques 15 years ago.

    Smashing worries a bit too much about the “look” of things when any successful web developer will tell you it’s the bigger picture that matters so much more. Do you design profitable websites that people love to use? I do, and have been doing so for over 15 years – my websites use HTML tables, deprecated JavaScript and even IFRAMES (!) and they all work, they are all secure, and they are all highly profitable.

    Remember, bigger picture, people…

    -1
  36. 3536

    Pretty basic stuff. What I missed is a simple pattern for implicit JS object orientation:

    function obj(options) {
    if (!options) { return; }
    var heir = new obj();
    heir.options = options;
    heir.init();
    return heir;
    }
    obj.prototype={
    init: function() { … }
    };

    This way, every call of “obj({…})” returns a freshly spawned object that will encapsulate its own state and scope.

    Another thing I missed is the great flexibility (and speed) of .replace(RegExp, Function) statements.

    Oh, and I almost forgot closures and the the .call and .apply methods.

    Other than that, nice article.

    0
  37. 3637

    jQuery is a JavaScript framework!

    0
  38. 3738

    Well written – thx!

    0
  39. 3839

    Krishna Upadhyay

    May 8, 2011 10:06 am

    It’s JavaScript world………

    1
  40. 3940

    Good stuff…. thanx.

    0
  41. 4041

    It took me some time, but I wanted to point that out. For IE7-8 (I don’t do 6) there is only “attachEvent”. And I have terrible times combining it with the method showed here.

    0
  42. 4142

    I use JavaScript to make a living. I have for a long time with small companies in the midwest, mid-sized companies in NYC, and major companies in the valley. Through this whole time, I must say you are the odd person out. It’s not what is right or wrong. It’s all about working on a team, and what is agreed on so the team members individually can all reach their max productivity.

    Spaces vs. tabs work better outside of GUIs, and believe me, A LOT people (me NOT included), use vi, vim, emacs, and a few other command line editors. Tabs make their lives a living hell, so I respect their wishes and use spaces.

    Ternary operation exists for a reason. People like it. Many people will agree in the real world.

    Overall, my advice is to get over that syntax hump. Read a lot of code, and work with a variety of people on numerous diverse projects. You will understand the “why” in a lot of this, get used to certain things, and your tune will change overall. Pretty soon you might even be minimizing semicolons, and putting commas at the beginning of line breaks (which would put a smile on my face).

    As for the article itself, I give it a 5.5 out of 10. It’s for beginners, uses some terms incorrectly (which I am also guilty of sometimes), but overall misses very basic important concepts. The major one of these is event propagation, which was already mentioned in the comments.

    -1
  43. 4243

    Hey, thanks for the post. Keep writing.

    0
  44. 4344

    I have written some articles on the same lines. Maybe helpful for some developers starting to get their hands in JavaScript.

    Regards,
    Bilal Niaz Awan

    0
  45. 4445

    These are all new things I’ve learned in the past few years in Javascript as well. You learn a lot by playing around with experiments, doing research online, reading the docs, reading articles like these.

    You have to totally immerse yourself in the languages you’re using to become a pro at it to maximize your productivity.

    Javascript is awesome. I learned it backwards. First from JQuery, then when I started building bigger things I started getting into more advanced stuff. Like JS’ OOP and so on.

    0
  46. 4546

    been teaching myself for years, not by reading tutorials, — and you would know from the tone in my voice as i say this, rather stubborn and perhaps sullen, yet gloriously, blissfully — not so much by reading articles such as this, but instead by concentrating the code itself.

    pages of it. fun. healing to a mind raised by and among and within the post modern soon-to-have-been-gleefully-dis-intermediated dumb-em-down-make-em-borrow-make-em-pay propaganda machine.

    your presentation of the work enticed me to read it, despite, (or perhaps because of), being a primer. well done. very clear. and i must say this is not only one of the few times that i wanted to read more of a work such as this — but also the very first that i wanted to read suchlike by a particular author. that would be you. so consider yourself complimented, and thank you for this little bit of the Great Work.

    -2

↑ Back to top