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:

Related Posts

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 topShare on Twitter

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

Advertising
  1. 1

    It’s obvious that the writer of this article has no idea about javascript programming and coding. What works in theory rarely works in practice. Smashing Magazine strikes again – this is a boring and useless article. As usual.

    -26
  2. 2

    Vitaly Friedman (Smashing Editorial)

    April 20, 2010 6:40 am

    I would highly recommend to read the article first before publishing such comments. We appreciate constructive criticism, but what you are writing here is just wrong. Please read at least the introduction and the biography of the writer – he knows exactly what he is talking about.

    Sorry, XLS, but it’s really sad to receive such comments over and over again.

    7
  3. 3

    Excellent example. The Apply functions deserves a place in this article as well…
    Along with Arguments and Prototype.

    One could then for example define
    Array.prototype.max = function() {
    return Math.max.apply(null,this);
    }
    so that [1,3,4,45,2].max() would return 45…!

    2
  4. 4

    I read the article and didn’t see where you’re basing your judgment on. Also, this is geared towards beginners and intermediate developers, so if you’re a JS expert and didn’t see anything particularly new, you shouldn’t be surprised.

    On a different topic: @chris heilmann – it would be fun to see an article on JavaScript scripting performance/optimization techniques. I just read a blog post by Nicholas Zakas that he wrote last year that made me go “aha” about optimizing loops by iterating on the items in chunks. I mean, the solution is so simple that you scratch your head and think, “Why haven’t I thought of that?” Even “basic” stuff such as declaring local variables when you access global variables more than once in your script would be a great read for people.

    1
  5. 5

    I can second you on the shorthand “techniques” and native functions. I’ve spent lots of time trying to figure out the fastest way to do something, and then someone telling me afterwards that JS “will do that for you…*blank stare*”.

    Anyways, good article. :)

    2
  6. 6

    Very disappointed with the quality of articles in Smashing lately …
    After the Hello world! in PHP, now comes a Hello world! in Javascript.

    Excellently written article btw, great for an introduction to javascript

    3
  7. 7

    I’m not even bothered to read this as I’ve seen this similar post title on way too many occasions. It’s starting to annoy me now.

    -2
  8. 8

    var numbers = [3,342,23,22,124];
    var max = Math.max.apply( null, numbers ); //342
    do the job as well (via http://ejohn.org/blog/fast-javascript-maxmin/ ).

    4
  9. 9

    Smashing Editorial

    April 20, 2010 6:42 am

    As you know, Marin, we are aiming for a variety of articles on very different topics. Could you please be more specific – what recent articles are you disappointed with?

    3
  10. 10

    The “revealing module pattern” idea is cool :)

    0
  11. 11

    Well i think its a good article for people with not much js experience (like myself).
    Always good to learn new stuff

    thnx Chris.

    1
  12. 12

    Much better article than the usual “Let’s learn jQuery!” article usually posted here. Here’s hoping some of the people who rely exclusively on libraries with no understanding of what they do take an interest in this article.

    0
  13. 13

    Anonymous functions are not JavaScript 101. I really enjoyed the article’s focus on JavaScript design patterns. I would even suggest going even deeper into JavaScript.

    Great Article!

    0
  14. 14

    Needs citation.

    3
  15. 15

    It’s ridiculous how some readers believe that smashing magazine and especially web design should be all about fancy graphics, visual inspiration and cuddly icons. As soon as you post something useful about web development or coding topics all this whiners (or wieners?) appear and leave their retarded comments about how bad smashing magazine got lately.
    I’m one of those users who appreciate the effort of each article and i’m sure that the content is always in some kind of way useful.
    Excuse my french, but go and watch teletubbies you f*tards, you are not worth it and you are far from being professional with such an attitude.
    At Smashing Magazine: Please mind that most of your readers who are satisfied and happy won’t leave any comment at all. Constructive critisism is a lot different from this and i’m sure that it appreciated by you. Keep up the good work.

    2
  16. 16

    Indeed, poor article. An example:

    Take “Math.max(12,123,3,2,433,4)”, this piece of code is often useless since it uses a constant list of arguments. Most people would assume the max function also accepts an array, after all, this is JavaScript we are talking about. So try “Math.max([12,123,3,2,433,4])”, it returns NaN. This would be a great start to explain how functions work in JS: “Math.max.apply(null, [12,123,3,2,433,4])”.

    Now THAT is some I wish I knew much earlier—not that Math.max exists.

    The example before contradicts this. OK, it perfectly demonstrates the use of a lambda method to sort an array in descending order and pick the first element as “max” (BTW: what if the array is empty?), but why not simply use Math.max? Maybe because it does not accept arrays?

    0
  17. 17

    Good article.

    For the module pattern, you can also encapsulate your application in an object, instead of a function. So instead of


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

    we can have


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

    Of course, this does involve refactoring the code more but you don’t have to return functions.

    0
  18. 18

    Dear Jabe,
    i get it! your js trouser snake is longer!
    But imagine this, (even if it’s really hard): not everybody is such a genius like you!
    There are people out there who just walk their first steps with js, and this article was supposed to give them a little bit of orientation.

    The only thing you are doing here is showing off what a smart ass you are…
    Please read my comment, especially line 5 from the bottom.

    cheers Mate

    0
  19. 19

    I thought I’d better take a side with SM on this one; I don’t think all the criticism (whilst not constructive) is really necessary.

    Lately I’ve been working on projects where it just makes more sense to use a library. After using jQuery for so long, you can forget the less-obvious fundementals of writing good native javascript.

    This article is obviously not aimed at javascript superheros, but it’s certainly useful as a refresher course when you don’t want to pull down a library for a few lines of javascript.

    Thanks for this well structured read.

    0
  20. 20

    Hi Marin, on the other side i`m glad for articles like this. I`m a web developer for 7 years but I`ve never seen article with exact examples of this type. From time to time I need reminders like Christian wrote here. And this is really useful for beginners too. So its better to learn them the right ways from the beginning. Christian thnx !

    1
  21. 21

    also note: if the functions are within an object, every reference from there to another variable/function of that object needs to be preceded with ‘this.’. So

    getMemberDetails : function (){
    return this.name; //not simply ‘return name’, as that will not work
    }

    0
  22. 22

    When did the readers of this site become such D#ckheads?

    1
  23. 23

    I’m glad Christian has written another article for SM, but I’m afraid I have a couple of critical points to share.

    Firstly, JSON is not the same as JavaScript’s object notation — sure, it’s a subset, but JSON is simply a data-interchange format. When you create an object literal and fill it with a bunch of properties you’re not creating JSON — that’s just an object. It’s quite a fuzzy topic, but I think you’ll find that there is some validity to my argument: http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/

    I think it’s important to maintain a high standard when it comes to nomenclature. It’s not called “ternary notation”; it’s the “ternary operator”, or more correctly, the “conditional operator”. It happens to be the only operator in JS that accepts three operands, and that’s why it’s commonly referenced as the “ternary operator”. Also, the Math object is not a function, it’s a regular object that contains a bunch of “static” methods, like “abs”, “floor” and “max”.

    I was surprised to see an entire section dedicated to Event Delegation, and not a single utterance of the words “bubbling” or “propagation” — If I was teaching Event Delegation I would start by explaining the fundamentals of DOM events, including how events bubble, and possibly discussing event capturing too.

    Oh, also, finding the largest number in an array of numbers is EVEN simpler than you’re supposed ne plus ultra. E.g. Math.max.apply(null, [3,342,23,22,124]) === 342 ….

    1
  24. 24

    Great article!

    I would like to say that not everybody that visit smashing magazine is a javascript Ninja and even people that have been working in javascript for a long time can see this like a review of our knowlage.

    It is a shame that people think this magazine is only for roundups or fancy graphics. Remember that web development is more than that.

    Christian Heilmann, what about an article in JavaScript performance?

    Great post btw.

    0
  25. 25

    You guys know about the behaviour of js… but not how to behave.

    0
  26. 26

    I love this article. I could go without the new fad of “X things i X’d before i X” title and format though.
    Because this has so much great useful information in it that i think the title really takes away from the content.
    Again, love the content, boo the title.

    0
  27. 27

    While I haven’t had time to look into this one, I would like to encourage Smashing to do more articles like this. It makes the site more interesting to me. Have a look at your search logs, I’m sure this is the kind of stuff lots of users are looking for.

    2
  28. 28

    You’re missing one of the finer points of the module pattern; variables declared inside the function are “private” and can’t (easily) be accessed from the outside. And as Willem Mulder mentions you won’t need to prepend “this.” to them when accessing them from the internal functions.

    0
  29. 29

    Please remove the comments from Marin Todorov and XLS. I have no idea what they are talking about.

    This is a great article, I have been a developer for over 5 years and I sure did learn a few things.

    0
  30. 30

    Thank you Smashing Magazine for this article!! It’s great! And all those people (@Marin, @Robbie, @XLS, etc.) whining about the articles, so what if every article doesn’t meet your needs.

    Why don’t you enlighten all of us with your vast knowledge on these subjects? I’d love to learn from an expert like you! Or maybe you have no clue what you’re talking about…

    -1
  31. 31

    ++

    I was thinking exactly the same thing: “It would have been great to show you could do Math.max.apply and use an array here. Missed opportunity.”

    0
  32. 32

    This was an excellent article SM. I’d love to see more articles on javascript design patterns and best practices.

    0
  33. 33

    Excellent article, Chris. One minor point is your array sort function will fail in some rare edge cases. I have a write up here: http://hurl.ws/1mln

    I have to think some of the negative comments here are either trolls or the work of emotionally immature people. This article is a great introduction to some key concepts that would have helped me heaps early on in my career.

    1
  34. 34

    I liked it. Javascript was a ‘necessary evil’ for me when my primary development was on the web (1999-2003) and I used it as little as possible..

    I just started tinkering with jQuery in the past week or so for me it was a timely article. It (and the other libraries) take away much of the pain of javascript. And its one of those technologies that falls somewhere between designer and developer in many places, so its a fit for Smashing as well. There are a lot of new technologies being used together, and it’s hard to keep up. While design is your bread and butter, I think this was a step in the right direction.

    I do have to say that I thought the knitting article was a reach, but I don’t expect every article to cater to me myself and I. And this article is much better IMO than just a list of images and links.

    0
  35. 35

    @XLS
    You’re an idiot.

    3
  36. 36

    Michael Campbell

    April 20, 2010 9:16 am

    Not to mention using an O(n log n) sort function for getting the max value, which even using the naive “this is bad” example is O(n).

    0
  37. 37

    As someone who has only recently begun makin the transition from designer to developer, there was a decent ammoint of helpful information here. Thank you.

    0
  38. 38

    These articles keep me coming back for more. I mean…yea, they’re basic but sometimes I tend to forget the basic methods and it’s the overviews that remind of important yet simple procedures. If you’re so underwhelmed by it, then write something creative.

    0
  39. 39

    To all haters out there:
    You were not born with knowledge of JS or any other programming/scripting language. You also learned it gradually. So, let others learn now.

    1
  40. 40

    Marcos Carrasco

    April 20, 2010 9:48 am

    Thank you for that!

    0
  41. 41

    I love it man! some of these i haven”t learned yet. thx a bunch!

    0
  42. 42

    Amazingly well written article. Your examples well support your statements!

    0
  43. 43

    I’m guessing it happened when SM stopped posting crappy ‘inspiration’ posts and started posting things that people can have genuine professional opinions on.

    Programming articles in particular attract a rather more robust breed of commenter. I’m actually all for it – if somebody thinks your programming knowledge could do with improvement, then nothing is gained by them keeping their trap shut about it. Sure, the “actually you’re wrong” posts might come across as dickish, but the geeks have never really been lauded for their social sensitivities.

    For the noobs who get upset because “we’re not all good at it!”, do stop and think about whether best practice debate is something that could help you. Believe me, you won’t become good at it if you’re not willing to pay attention to the sources of conflicting advice where they occur.

    Anyway, good article – but I wish everybody would stop using that fcking ternary operator everywhere, seriously. You can just about get away with it if it has a measurable impact on processing time, but for general usage just _don’t_. It is horrible for code clarity.

    0
  44. 44

    Thanks very much for this. I’ve only been writing javascript for a short time and i enjoyed your breakdowns and examples

    0
  45. 45

    I’m surprised at the comments saying that this is a simple beginner’s article. If you read it carefully, you will discover that it comments more deeply on topics that are normally in beginner’s articles.

    I think the people moaning in the comments only looked at the topics, and did not read what the article had to say about those points. Consider the original material in the “revealing module pattern”.

    That kind of new programming pattern is not a “hello world”. As a programmer of 30 years, I can say this is not a beginner’s article. It is simple, and it is deep.

    1
  46. 46

    Arnoud ten Hoedt

    April 20, 2010 11:23 am

    A javascript technique I grabbed from the excellent Backbase architecture is to start solving crossbrowser CSS issues by adding classnames to your [html] tag based on the browser that is available.

    So in firefox 3 you get [html class="gecko gecko3"], while in internet explorer 8 you get [html class="ie ie8"].
    Such detection functions are easy to write and hook onload for any javascript framework, and provide you lots of additional gun powder when solving crossbrowser css issues.

    And in the case of javascript not being available alltogether I still think you should nowadays consider to redirect users to a non-js/accessible/mobile skin of your website.

    0
  47. 47

    Oh yes, I second that… no better word to describe you XLS

    2
  48. 48

    It would be really nice if we could see a demo with each script!

    0
  49. 49

    One big thumbs down to all the naysayers. I’ve come across a lot of articles on here over the past year that have been ‘basic’ or rudimentary in /my personal experience/. I generally scan them and move on rather quickly. I don’t however feel a need to trash on the author.

    This time I’m on the other side of the coin; I woke up the other morning and decided it was about time I brought my understanding of JavaScript and AJAX up to speed with the rest of my web development background. I’m learning fast thanks to being rooted in very similar object oriented languages, but every language has its own conventions and constructs that can be frustrating due to their minor differences.

    This article was a great insight into some of those differences for me and will go a long way to helping me add the language to my arsenal. Thank you Smashing!

    0
  50. 50

    Jan Philipp Pietrzyk

    April 20, 2010 12:05 pm

    This is a bad solution! You just have to start over every time a new Browserversion comes out. Not only is it you responsibility to check your CSS but also your JS-Detection. Libraries walking a different path, and so should you. Just take a look at the bunch of CSS Frameworks out there, which all solve this in a pure css-manor.

    If this became common practice, this would even hold the web and Microsoft more than it does now, there are some excellent blog entries in the IE9 Blog describing the faulty behavior in detail.

    A and take a look at the other Yahoo guys blog: http://blog.ginader.de/archives/2009/06/30/The-5-Layers-of-Web-Accessibility.php ;)

    0
  51. 51

    I agree. The concepts covered are far from difficult, but at the same time, I rarely see things taught this way. It’s no wonder the vast majority of vanilla javascript on the web these days is just plain horrible. Javascript is easy to pick up, but it’s so full of cruft that it’s difficult to learn things the right way. Christian is doing us all a favor by exposing some of the good parts of Javascript that anyone can pick up on right away.

    0
  52. 52

    …You can, but then you have everything publicly accessible, unlike in the Module pattern, where you can hide things.

    0
  53. 53

    Not to discredit/ignore anything else that you said above the last paragraph (what you said was well-stated)… but to each his own–I find ternary operators easier to read (or maybe easier/quicker to write?) than if/else’s.

    0
  54. 54

    I found this article pretty interesting.

    It’s a shame that the internet is so over-run (and somewhat spoiled) by keyboard warriors who just log on to have a rant and vent their pent up social angst. they should rejoin their chums on youtube and relentlessly argue about petty nonsense there instead.

    There can surely be nothing wrong with a web blog which targets a broader audience with a variety of topics at different professional levels.

    0
  55. 55

    “adding classnames to your [html] tag based on the browser that is available.”

    Huh, that’s actually a pretty handy tip, thanks for posting that.

    One thing to be aware of with it though is that IE6 (always with the IE6 >:[ ) is hopeless with class chaining, only taking the final class in the chain to act upon – so it’d possibly be safe to assume IE6 for base structures and only dynamically chain classes for the modern browsers.

    Good comment though, thanks again :)

    0
  56. 56

    Thank you for the article, no matter how professional you get in something there’s always a chance to forget principles, articles like this are good reminders. Coding technics can easily become habit for a coder and if it starts wrong it will be hard to fix it.

    0
  57. 57

    I love javascript and some great shortcuts shown here. jQuery saved the web…

    1
  58. 58

    @James Good points about JSON & event bubbling/propagation. Knowing event bubbling/propagation is very critical if you are writing JS for interactive UI.

    0
  59. 59

    why dont you guys write another article about how great Apple is and how much Adobe sucks and how fast Flash will be gone from 99% of the worlds browsers.

    Here is quality content on JavaScript….

    http://net.tutsplus.com/tutorials/javascript-ajax/crockford-on-javascript-the-complete-series/

    …..also IPad

    0
  60. 60

    I believe this is how modernizr works. “Modernizr is a small JavaScript library that detects the availability of native implementations for next-generation web technologies.” It adds classes based on the available browser features allowing you to reference them specifically. Check it out.

    0
  61. 61

    I wish I had this article when I first pick up ExtJS and JQuery.

    The Javascript frameworks looked like an alien language to me at the time… Took me days just to get up to speed.

    Keep up the good work, SM.

    0
  62. 62

    This article reminded of Gary Larson and his ‘Far Side’ series of one panel comics. The one with a man talking at a dog and all the dog hears is his name – ‘blah blah blah Rex, blah blah blah Rex’.

    I dont write or pretend to know Javascript but I at least read the intro and tried to follow some of the examples – ‘blah blah blah JavaScript’. This article isn’t for me, but knowing the quality of articles that appear on Smashing I was always going to take a look. Keep up these kinds of articles.

    Regards – Rex

    0
  63. 63

    var numbers = [3,342,23,22,124];
    numbers.sort(function(a,b){return b – a});
    alert(numbers[0]);
    —————————–
    Yes, this works. However, it pays no attention to performance. This method will take orders of magnitude longer to execute than the “long” form that only loops over the array once.

    Remember kids… fewer lines written does not necessarily mean better code. The author forgot how much is actually happening inside the sort() function. Just because you don’t see the code, doesn’t mean it isn’t there.

    1
  64. 64

    Great work Chris, I agree that debate should be had about best practice (and the article updated if errors exist), but I have to admit I get annoyed by a few of the JS geeks who flame away but are unable to back up their comments with substance, explanation and examples. This is a professional forum not a zoo, If code monkeys are going to fling poo at each other at least prove your a monkey and no just a twisted individual who likes flinging poo.

    0
  65. 65

    Best article on Smashing in ages, I actually learned something!

    More of these, less articles about knitting :)

    0
  66. 66

    I personally find ternary statements perfectly clear, I’m sorry that you don’t.

    Honestly, you could make the same statement about ‘for’ vs ‘while’ loops. They can both do the same thing but ‘while’ loops are generally easier to read. Surely at some point though, you have to accept that most people can understand what this means:

    for (var i = 0; i < 10; i++)

    0
  67. 67

    This is a very useful article for developers of all levels. I am a javascript novice and will definitely pick up on some of these techniques as well as look further into them. Please keep articles like this on deck and in the queue @smashingmag! :)

    0
  68. 68

    kelvinwebdesigner

    April 20, 2010 6:59 pm

    First i would like to congratulate the author of this excellent article.2nd sm is doing a good job bringing articles all kind of levels and shapes. Stop criticising guys if you cant do no better!

    0
  69. 69

    Great article for beginners , i like it!

    0
  70. 70

    Great, especially about JSON, I had a hard time figuring out javascript frameworks until I realized that they use the JSON format which is why all the code “looked funny”. I agree that frameworks make it easier to deal with cross-browser issues.

    0
  71. 71

    Lokesh Yadav aka. Lucky

    April 20, 2010 8:20 pm

    Thanks a lot for “short & knowledgeable” article Chris.

    0
  72. 72

    Article’s content is not so much the problem .

    The problem is the context: Clearly explain who should read this article. Novice, intermediate, expert, etc… Then readers can set their mind before reading. There is a difference between 7 novice tips and 7 experts tips. You should make it clearer both in the article title and in the introduction ( given the introduction, you do expect more than what the actual content provides). Maybe an icon or something visual representing the context would be good too.

    And everyone will happily read, and write constructive comments.

    0
  73. 73

    your first max requires ~ n operations, sort requires ~ n log(n) operations so it does not look pretty.

    0
  74. 74

    I’d prefer to check for Array.prototype.max existence before such prototyping in case when it will be realized (ES5?).

    1
  75. 75

    Great Article Chris

    Thank you so much. learned a lot of things I wish I knew earlier. Keep up the good work and looking forward for your next article on javascript. writers like you and articles like this keep me coming back to SM its a shame some people just don’t appreciate. :)

    0
  76. 76

    Hello,

    I understand Marins point. If you are an advanced developer, you don’t need such articles. For my self I would also prefer more articles witch go deep into the material (very rare lately). But for beginners those articles are very usefull and the articles mostly refreshing old things u might have forgotten.

    –Just in case u have forgotten, who the hell you are ;))

    3
  77. 77

    Very nice article there… suddenly feeling Nostalgic :)

    0
  78. 78

    Fine Tutorial, very useful to me ..

    0
  79. 79

    I love this kind of articles!

    0
  80. 80

    I will hunt you both down and kill you! KILL YOU! I bet you both use spaces instead of tabs, too! And your bracket positioning will be all wrong!

    -1
  81. 81

    Ok, I think this article is unuseful. Why?
    If you just sad:
    1. Buy books and learn basics
    2. Visit jquery (or prototype or other framework) homepage and learn it

    It would be much useful, because everything what you’ve written is about the same:
    How to use (function(){}) (yes config object and isn’t about this).
    And I think jquery is more than just library, it’s framwork which help’s you with Maths operations, AJAX etc.

    And article about PHP was bad too. Because you started with basics (Hello world!) and finished with additional library curl! I have 5 years PHP experience but I haven’t used curl yet (you can use file functions instead).

    I will be very pleased to find some articles about typografy (design) theory in SM or Silverlight examles but I can see the same icons in 3 posts (so what is new? what is fresh?)!

    I think that you can make it all better.

    Tom

    0
  82. 82

    I just looked into a dictionary and guess what? It seems that there is no word that would describe these people! Excuse me, d*cks!

    Here you find FREE QUALITY CONTENT.Do you see that capitalized text?

    When i read these comments i was like…d*mn…internet users are so spoiled in 2010!

    Sincerly, i liked this article and i am thankful for what Smashing magazine does!

    0
  83. 83

    I think this is a very unprofessional article. For example on Json snippet, John Frusciante is not the current lead guitarist of the Red Hot Chili Peppers so it’s all wrong.

    ;)

    -1
  84. 84

    I can’t believe why people are criticizing such a great article :(

    0
  85. 85

    Luigi sorry, but in my opinion there WAS free quality content. Sometimes appear really really great post in this site, but just simetimes.

    Internet users are not spoilet, but quality of design is going down. So do you know why?
    Because eveything is instant … like soup … They just say How and not Why. They don’t learn you how to make brilliant icons, they give it to you … They post tutorial, and show How to do it, but they don’t say Why this color. There was color theory – great post, but now we can see mish-mash articles about PHP and JS.

    I want to be great designer, no just look to great designs. Just look at this site and Networks articles. Everything is ‘Best’, ‘Most …’, ‘Awesome’, ‘Great’, ‘Fantastic’ but really? They make 3 or 4 articles when reffer to the same pages, for example SOFA. They have got nice clean design, but why are they in 3 or 4 articles?

    And I am very thankful for what SM does too, but i think they can make it better, because they did it better and now it seems like they fall a sleep.

    Tom.

    0
  86. 86

    To those leave the bad comments about this articles. Why don’t you write a good one and let other people to criticize yours but without appreciate how much effort you put in and how useful to other people.

    0
  87. 87

    Donald Dolandson

    April 21, 2010 4:18 am

    People really should cut the author of this article a break.

    Yes – It may be far too basic for YOU personally but it is extremely useful for many OTHER people. Every single article on Smashing can’t be expected to cater for you and you alone, the audiences abilities and interests are so diverse it just wouldn’t be possible.

    If you can take something from it – great, if not why not take the time to find something more advanced and read that rather than posting about how this article is too simple for you?

    0
  88. 88

    Vipul Limbachiya

    April 21, 2010 4:29 am

    Wonderful article!! I’m involved in javascript development since 3 years, learned a lot till then but such articles are at real help to beginners and novice developers.

    Thanks

    0
  89. 89

    Thanks for the article. As a designer who generally uses javascript libraries I found it really interesting.

    1
  90. 90

    “Disclaimer: while both of the event examples above work in browsers, they fail in IE6.”

    Technically your example for event delegation shouldn’t work in any version of IE. IE 9 will be the first MS browser to implement addEventListener.

    0
  91. 91

    Nice and detailed article. But it’s a shame that the official recommended notation of curly brackets (underneath and not diagonal) are still not in use, even after “written dozens of articles, book chapters and one full book”.

    -1
  92. 92

    Hence the year is defined as 2009 :)

    0
  93. 93

    Using

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

    To get the maximum of an array this way is pure crazyness ; in terms of algorithmic complexity, you’re moving from O(n) to O(n.log(n)). That means that you’re basically multiplying by 10 (actually more, since the sort implementation always exceeds strict nlogn) the time needed to retrieve the maximum of a 1000-elements array.
    Provided that usual sort implementations have a constant factor of about 25 to 35, it means that on a 1000-elements set, you’re multiplying the time needed to extract the max by 350. Great tip indeed!

    I’m pretty disappointed that Smashing does such a mistake…

    0
  94. 94

    It seems that for every post on SM, some idiot simply has to make the “oh, this is waaaay too basic for me” comment.

    Well, I appreciate the work SM and their contributors put into this great FREE resource for the design community. That’s right, COMMUNITY, as in for everyone, not just the handful of gurus out there.

    Some of these self-appointed experts should perhaps contribute articles to this community rather than criticising others for doing so. Either that or simply stop reading articles that are obviously not aimed at them.

    Keep up the great work SM!

    0
  95. 95

    This was great for some of us blossoming Javascript developers. Sure, could probably pick it apart, but hella useful.

    0
  96. 96

    Wow, where is this officially recommended notation of which you speak? The only one for JS I know is Crock’s and he is happy to use diagonal – http://javascript.crockford.com/code.html – even proves a point with a return having the wrong return format if you do it.

    Quote: A return statement with a value should not use ( ) (parentheses) around the value. The return value expression must start on the same line as the return keyword in order to avoid semicolon insertion.

    0
  97. 97

    The Author is trying to give everybody a push towards java script. the language is nice. It is not fair to criticize him with out reason or thought.

    many people write the book and you are not supposed to compare it in the public, it is more or less cheap to do that.

    0
  98. 98

    A short sighted and elitist comment.

    Good job Smashing. I learned a couple new things here.

    There are other sites for elitists.

    1
  99. 99

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

    0
  100. 100

    I’m agree with you on some points.

    0
  101. 101

    Python ftw

    0
  102. 102

    I have been developing since the early 90′s and recently (last 7-8 years) got into the web development from application development. I would say that I like the articles I have seen, mostly…but lately there seems to have been a shortage. Anyone who thinks that a “basic” article is below them because of their experience is doomed to the stage they are, we learn by exploring and re-exploring…from time to time we need to check the facts we think we know.

    Having said all that, I wanted to reply with some article requests. I know it can be difficult to provide such content, and ya’ll do a magnificent job of providing good content.

    One topic I think would be very good has to do with database normalization in relation to the developer. If you read a lot of articles on the topic, you find this hard line of some developers saying normalization is worthless and others saying you need 4NF all the time. I think it would be good to see an article that went over normalization (in regard to the developer) and when it’s good as well as when you might look at denormalizing a structure…

    I think I’d also like to see some articles on .Net development…there have been a lot of good additions to the languages over the past few years, and yet there are very few articles on some of the topics…although I’m not sure if I ever remember seeing a Smashing Magazine article on .Net development, so maybe it’s not in ya’lls lineup.

    All that being said, I think the only thing I’d like to see from Smashing Magazine are more articles…I think what I have seen of your articles is good and I’d like to see more…

    (Edit) Oh…and I think abstraction layers would be a great topic as well…not to mention development methodologies. There are a TON of new developers out there and many of them seem to think little of using standards or proper methodologies, etc…something to illustrate a few good techniques or something would be cool…explain how properly devised code structure can make implementation and management of the code during it’s lifetime a LOT easier…

    Ok, sorry for the book-response…hasta

    1
  103. 103

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

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

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

    0
  106. 106

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

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

    A nice and useful article

    0
  109. 109

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

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

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

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

    nice article!

    0
  114. 114

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

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

    goog article!

    0
  117. 117

    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.

    -1
  118. 118

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

    Tom.

    0
  119. 119

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

    0
  120. 120

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

    Roshan Bhattarai

    April 23, 2010 8:40 am

    XLS stop talking nonsense.

    2
  122. 122

    Frusciante is not in Red Hot Chili Pepers anymore =P

    0
  123. 123

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

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

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

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

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

    0
  128. 128

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

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

    Nice
    Thanks very useful

    0
  131. 131

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

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

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

    0
  134. 134

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

    0
  135. 135

    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…

    0
  136. 136

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

    jQuery is a JavaScript framework!

    0
  138. 138

    Well written – thx!

    0
  139. 139

    Krishna Upadhyay

    May 8, 2011 10:06 am

    It’s JavaScript world………

    1
  140. 140

    Good stuff…. thanx.

    0
  141. 141

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

    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.

    0
  143. 143

    Hey, thanks for the post. Keep writing.

    0
  144. 144

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

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

    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.

    0

↑ Back to top