
JavaScript Things I Wish I Knew Much Earlier In My Career - fogus
http://www.smashingmagazine.com/2010/04/20/seven-javascript-things-i-wish-i-knew-much-earlier-in-my-career/
======
snitko
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.

~~~
pavel_lishin
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?

~~~
dpritchett
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._ "

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

~~~
mootothemax
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.

~~~
Daniel_Newby
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.

------
moron4hire
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?

~~~
username3
A list of everything we should know.

~~~
moron4hire
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.

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

~~~
dpritchett
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...](http://jmesnil.net/weblog/wp-
content/uploads/2009/09/RzRcw.jpg)

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

~~~
darshan
Just an FYI, in case it wasn't a typo: you mean _whet_ , not _wet_.

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

~~~
dpritchett
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.

~~~
mdg
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.

------
Tichy
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]);

~~~
willwagner
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.

------
daleharvey
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)

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

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

~~~
jerf
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.

~~~
jlangenauer
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.

------
tuacker
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)

~~~
mattyb
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?

~~~
tuacker
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!

------
latortuga
"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?

~~~
ewjordan
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.

~~~
latortuga
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.

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

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

~~~
stan_rogers
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.

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

~~~
camtarn
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
:)

------
d0m
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 :)

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

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

~~~
nhebb
_"Associative arrays" is a confusing name for objects_

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

~~~
Silhouette
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.

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

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

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

The author has clearly not had to use contentEditable :)

------
poundy
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...](http://www.webdigi.co.uk/blog/2009/javascript-gotchas-listed-to-
help-avoid-mistakes/)

------
apphacker
Uh, his handler could do with a closure.

------
frevd
YAWN! n00bz, you really bore me here.

------
zeeone
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?

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

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

