Hacker News new | past | comments | ask | show | jobs | submit login
JavaScript Things I Wish I Knew Much Earlier In My Career (smashingmagazine.com)
161 points by fogus on April 20, 2010 | hide | past | favorite | 68 comments



Maybe I'm just a douchebag, but isn't all that stuff in the "Javascript: The Definitive Guide" book? Read it once (at least the part that's focused on the language itself, not DOM) and you know it.


Also on the web, in a billion places. I'm always wary of people who are tweeking over Math.max - how could you not know that exists?


The article gently suggests the importance of learning all you can about the math and string libraries. It's not meant to imply that the author discovered them only yesterday.

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


If you spend any time at all researching Christian you'll find out he's written 2 books on JavaScript and contributed to several more, while speaking prolifically at conferences on the subject.

As a colleague and friend of mine, I can tell you he's trying to be an educator and help other people become better coders. If that means he's aimed some stuff under a line for "good" that's because he's trying to help people get over that line.


Remember that everyone starts out as a beginner.


I'm in favor of reposting this forever or until every JavaScript developer knows it. Whichever happens first.


Yeah, maybe a bit of a douchebag. I think it is an elite crowd here so this isn't really at all topical.

But, smashingMagazine puts out some awesome content (albeit mostly link rolls, but well illustrated), I have a hard time criticizing them.


If there's one book every js developer should get, it's that one.


If there is one book every JS developer should get it's "The Good Parts".

Completeness is not the same as 'bestness'.

Doug's book tells you what you should know, Flannigan's book tells you what you can use.


I disagree 300%.

"The good parts" is opinion and commentary. It's not fact.

I want hard facts about what the language permits. I can make my own mind up about what is good and what is bad thanks.

"The good parts" is an interesting read once you know the language, but I certainly wouldn't recommend it as a first book on js.


In that case please don't read any books about patterns, or best practices.

You might be the best programmer on HN for all I know, but personally I'm willing to admit Doug's decades of programming and international reputation might mean he can teach me something, without me having to learn it the painful way.


>> "In that case please don't read any books about patterns, or best practices."

I don't. I hate naming things as patterns with a passion FWIW. I'm not really sure you can really learn good taste from a book :/ All you need is the language reference, and years of practice...


The excellence of this article has caused me to reevaluate my attitude towards Smashing Magazine. I formerly knew it as a source for "50 Sweet Free Wordpress Themes" writeups and thus I largely avoided the place.

Really a good article, especially for a developer like myself who doesn't do all that much JavaScript.


Over the last year we completely re-evaluated the quality of our articles and we set up new quality standards and guidelines to meet the expectations of our readers. We are trying to get better all the time. And we are always glad to get constructive criticism and feedback from our readers. Thanks for visiting Smashing Magazine.


I'm really torn on my feelings about this article, it's mostly great, but the example of anonymous functions grates with me. I think it's a flawed example as it takes readable code and turns it into an unmaintainable mess, when the natural solution would be to use an object in the first place.


I agree. Just use proper objects and start internal member names with an underscore. Yeah, you cannot trust idiots not to misuse the internals, but they'll do worse with returning objects that close over function-local variables.


I would not call this article "excellent." His event handler doesn't use a closure and the first example is simply an object literal.


It's a problem that these things were surprises to him late in his career. Judging from the comments in this thread, even amongst a technical crowd there is still a relative lack of understanding about JavaScript. What can we as an industry be doing to make sure that more people are learning their tools properly and not reinventing wheels?


A list of everything we should know.


One need only throw a stone at Amazon.com and hit several dozen books that are essentially just that. Obviously, the existence of that sort of information isn't enough. Something more needs to be done.


good tips, if any of them are new, get "Javascript the good parts", it's an awesome book, and not too long


For prospective buyers who are still on the fence there's a handy 1000-word review comparing and contrasting The Good Parts with the Definitive Guide recommended above:

http://jmesnil.net/weblog/wp-content/uploads/2009/09/RzRcw.j...


I just bought both. The Good Parts to wet my appetite for JavaScript and the Definitive Guide to have a (hopefully) complete language reference.


Just an FYI, in case it wasn't a typo: you mean whet, not wet.


I think you meant to link this: http://jmesnil.net/weblog/2009/09/28/how-books-shape-my-appr... but you linked to the image in the page instead.


A picture is worth...


In they article, they mention ternary notation. I personally wish that people didn't use it. While it's great for saving (a little) time, it really muddles the readability of the program IMHO. Its far too easy to simply skip over it as a simple assignment operation.

There are a lot of gems in this article though (aside from that).


"Its far too easy to simply skip over it as a simple assignment operation."

This can be mitigated with parenthesis around the conditional statement.

"ternary notation ... [is] great for saving (a little) time"

I like it because it allows for immutable variables (enforced by fiat, of course), without writing four lines of "if ... else .."

That being said, it can be abused: http://www.google.com/codesearch?hl=en&lr=&q=%22%3D%...


One of the more delightful moments in my programming career was seeing that ReSharper could convert ternary notation to the (sometimes) more readable if/then construction automatically.

I'm pretty sure that other automatic refactoring tools can do the same.


Let me present an argument in favor of the ternary operator. tl;dr -- It is an abstraction on a conditional assignment pattern.

We start with your "readable" approach:

    var a;
    if (condition(x)) {
        a = 4;
    }
    else {
        a = 5;
    }

That has all the glory of line noise, repetition, and a declaration to make our language happy. This example is a little exaggerated. We can make our declaration more useful and our condition more of an exception:

  var a = 5;
  if (condition(x)) {
      a = 4;
  }

That is still two assignments or, rather, the "a =" pattern repeated. And that is just for a trivial single branch. How can we abstract that out? You have two options. For simple conditions, we can do this:

  var a = condition(x) ?
              4 :
              5 ;

It might be better to abstract it out like this:

  var a = value_for_a_with_environment(x);

Sure, you may be using a ternary operator or if...else underneath the hood in value_for_a_with_environment(), but give that function a relevant name, and someone can get the gist without having to know the details.

It could just be arrangement and syntax we despise. Here is another language's approach to the ternary operator:

  (setf a (if (condition x)
              4
              5))

Or with consideration given to the environment:

  (setf a (value-for-a-with-environment x))

Once I learned some of the value and abstractions of functional programming, I stopped feeling the ternary operator's use was ugly and realized it was more that I hated the line noise involved in using it. That colon looks a lot like a semicolon.

Also, it is limited. In nontrivial code, I have seen cascades of ternary operators.

  var a = cond1(x) ?
              4 :
              cond2(x) ?
                  5 :
                  cond3(x) ?
                      6 :
                      7 ;
or

  var a =   cond1(x) ? 4
          : cond2(x) ? 5
          : cond3(x) ? 6
          :            7 ;

Pick your favorite arrangement.

We really want a non-binary-looking structure like this:

  (setf a (cond (cond1 4)
                (cond2 8)
                (cond3 12)
                (t nil)))


I agree. I've never used ternary notation regularly so it always takes me out of the flow when I'm trying to decipher someone else's source.


I cringe when I see a simple if-else, which does nothing but assign a value to a variable depending on the condition. That is the best use case for a ternary operator, in my opinion.

However, I have noticed that I tend to use them liberally, and have since reverted back to if-else when there is something more than "simple" going on in the condition or post-condition.


The sorting approach to extracting the maximum element seems inefficient, especially as they mention Math.max as the next example. This seems to work, too:

Math.max.apply(Math,[3,5,1,7,9]);


I was just typing a similar comment when I saw yours. In general, learning how to use "apply" is a very useful technique for someone coming up to speed in Javascript.


the most important (and non obvious) one in this I think is delegated events, they are invaluable when working with dynamically generated content.

I was always confused at why mouseover / out events bubble in the insane way they do, now I am glad for the behaviour (I just wish enter / leave came sooner)


My favorite surprise of JavaScript of all time: It has no integer type.


Crockford didn't create JSON any more than Al Gore created the Internet. He coined the term and evangelized the use of JSON as a data format.


Yes, he did. JSON is absolutely positively NOT "whatever Javascript eval will accept as input and return a data structure for". It is a rigidly-defined subset of that, and the rigid definition of it is one of its significant advantages over several competing formats. Crockford created the rigid specification and JSON is the better for someone with experience having created it. Someone of lesser experience might have specified it less rigidly and lost much of the advantage thereby.

(YAML died on fuzziness in the specification mistakenly perceived as virtue. "YAML's not dead!" Compared to JSON, it is, and thank goodness.)

Incidentally, if you aren't using it strictly, you're losing some of the advantages yourself. If your parser accepts single-quoted strings, or even worse if your serializer generates them (ick!), just as one example, you're in some trouble, even if it all works for you right now.


It wasn't just fuzziness, it was outright whimsy in the YAML spec. Interpreting the string "Yes" (and "on") to actually mean a boolean true is one of the dumbest things I've seen in any specification, anywhere.


And Crockford always insists he "discovered" JSON. So please don't misrepresent him, based on the words of someone else.


I hate every single time I see that. JSON as a data format has been in use forever in various languages.


I'm starting a new project as soon as my current one is finished based on php + javascript. Can anyone suggest good books and/or websites for those two to get started as I never really worked with either of them?

Edit: Apart from the two already mentioned in this thread. (Javascript the definitive guide and javascript the good parts)


Eloquent Javascript is a really great ebook.


For PHP: PHP and MySQL Web Development, 4th Edition by Welling and Thomson. Learn about PDO and parameterized queries and such from the online docs; the book treats security poorly. The Web Application Hacker's Handbook would probably be a nice third book if you're feeling indulgent.

For JS: JavaScript: The Definitive Guide, 5th Edition by Flanagan. Until Secrets of the JS Ninja (or the Rhino book's 6th edition) comes out, then get those.

Out of curiosity, what have you worked with previously?


I haven't had much of real world experience until recently. I learned coding in school. We started with C then C++ and later C#(.NET) and Java (often in junction with MySQL & Oracle for which we had an extra class also). In between I remember a bit of the ancient arts of COBOL and CICS. I got into Obj-C when I switched to Mac and tried to get my feet wet with something on my own. Though I created nothing in particular with it.

It's just recently that I started working on a real project (C#) and it's been fun so far and I'm eager to finish it and get onto the next thing.

Thank you for the sources!


I found w3schools and tizag to be two of the best free web resources. JavaScript Kit goes into things in a little more depth with, IMO, better examples.

I highly recommend taking the scripts in the tutorial apart and testing to see what happens. No matter how much theoretical reading or tutorials I did, nothing came close to actual hands-on coding.

Best of luck in your project!


Thanks for the resources! I agree with regards to hands-on coding. I usually use books to learn the best practices of a certain language and to get a basic understanding. Nothing beats learning something new by solving a real problem.


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

One sentence explaining that JS doesn't have variable scope proceeded by a sentence explaining that it actually does have scope? JS absolutely does have scoping rules. The follow up to this sentence (the section labeled "Anonymous Functions And The Module Pattern") seems to be ignorant of the presence of prototypes (in a prototype-based language!) and uses a needlessly complex and confusing way of explaining how to expose functions. What's wrong with the prototype?


Re: scope, I think the author was mainly complaining that Javascript's scoping rules tend to err on the side of global visibility, rather than following the typical approach of scoping variables as narrowly as possible. Certainly it has scoping rules, it's just that they're unusually global for a language with Algol style syntax, and that makes it a common gotcha for people coming to JS from other places.

What's wrong with the prototype?

Nothing too bad, I suppose.

Making things private is a little bit cleaner when you use the anonymous function/module method. By default, none of the methods are visible unless you explicitly expose them, whereas with a normal Javascript object you end up jumping through hoops to make private class methods actually be private - those hoops pretty much match what you do with the module pattern anyways, so...

More importantly, the "needlessly complex and confusing" way of exposing functions (I don't necessarily disagree that it departs from "write what you mean", but I don't know that it's either too complex or confusing, it's a pretty simple pattern and often results in shorter code than prototyping would, esp. with private functions and data) is used just about everywhere when you work with other people's Javascript libraries. So it's a good thing to be familiar with it, as you're going to be looking at it almost every time you open up the source for any modern JS library.


Regarding your (and my) last point, I mean confusing in the sense that if you are returning some object with (as in his example, differently named) references to internal functions, it only makes it more difficult to track down code later. Worse for the coder, worse for the maintainer, and unnecessary.


The article itself is quite useful, but a warning on the sort tutorial he links to (http://www.javascriptkit.com/javatutors/arraysort.shtml). Contrary to what it says, you cannot reliably shuffle a list by doing:

  myarray.sort(function() {return 0.5 - Math.random()})
This just makes every comparison return a random value, which may or may not produce particularly random results, depending on the sort algorithm. It's exactly the bug that bit Microsoft in their not-very-random browser shuffle screen.


Ah, how clear. A Car is a generic object (clearly an English object given the spelling of its attribute names), with untyped attributes.

The thing I wish the JavaScript community knew much earlier in their careers was actual software engineering knowledge, such as Object-oriented, or at least typed, languages.

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


Dynamic weak typing is probably JavaScript's greatest strength, not a weakness. Grokking this, you can also begin to see reasons why schemaless databases can be of great utility.


I think you didn't learn Javascript but you picked from from the streets and that is why you didn't know what you mentioned.


As Crockford comments, it's remarkably easy to get by in JavaScript without ever actually sitting down to learn the language. There's a lot of weird and funky JS out there written by e.g. Java programmers who only use a very small subset of the language's features - no closures, no object literals, and so on.

I second the recommendation of JavaScript: The Good Parts - it's a great book :)


Even if a bit newbish as other comments said, I found the article really well explained and I'm sure it helped lots of people. Good explanation, good code examples, great tips and great recommendation. Even thought I haven't learn that much in the article, I wish more article would be written like this :)


>“Associative arrays” is a confusing name for objects.

And don't forget the `hasOwnProperty` test when iterating over the keys.


"Associative arrays" is a confusing name for objects

That line makes me think the author doesn't know what an associate array is.


I think what he means is that it's not actually the array you're working with, so the name is misleading in this context. It's the underlying object. So if I have

var a : Array = []; a['property'] = 'value';

, then I'm setting a property of the object, not an element in the array. It works just as well with

var b : Object = {}; b['property'] = 'value';


JavaScript doesn't make the same distinctions between numerically indexed arrays, string-indexed associative arrays and objects that you would see in most other languages. This explains a lot of the perceived oddities of JavaScript to programmers coming from backgrounds working with other programming languages, e.g., why calling sort() on an array of numbers doesn't do what you might expect and why the for-each loop in JavaScript iterates over indices rather than values.


The same is true of Lua, except it recognizes when you have consecutive integer keys and implements it as an actual array.


Just for the record, the concept of the reptilian mind isn't from Godin. It's an old philosophical thing.


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

The author has clearly not had to use contentEditable :)


This is a nice list. Thanks. Also check out these Javascript gotchas that can save you time http://www.webdigi.co.uk/blog/2009/javascript-gotchas-listed...


Uh, his handler could do with a closure.


YAWN! n00bz, you really bore me here.


He says: "I’ve been writing JavaScript code for much longer than I care to remember." And he didn't know about "var direction = x < 200 ? 1 : -1;" ? Really?


"Here are some of the “aha!” moments I’ve had in the past"

He doesn't say how long ago in the past.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: