views:

732

answers:

13

OK, maybe "master" is a bit strong of a word, but I'd certainly like to get better at it. I can get things done with JS for the most part, but I've always had a nagging feeling that my knowledge in the language is lacking.

I believe the main problems I have with Javascript are:

  1. Inconsistent behavior across browsers
  2. Event-driven programming in general
  3. Behavior of anonymous functions
  4. The keyword this

1) is (for the most part) not JS' fault and can be "solved" by using frameworks like jQuery or prototype, but 2, 3 and 4 are concepts that I can't fully grasp.

How can I have a deeper understanding of those and other "gotchas" in JS?
(links to helpful resources very much appreciated)

+5  A: 

After writing my own implementation I pretty much know every little detail about the language. Now if that's not your bag you'll simply have to write lots of code.

ChaosPandion
grrrr ... downvotes without comments are so pointless. This isn't the best answer ever but the basic message - "write lots of code" - is in fact a correct one.
Pointy
Not my downvote, but this is not an answer it's an attempt to impress someone I suppose? It doesn't do that though, since in practice you'll deal with the quirks in the browser implementations that already exist and are widely used on a daily basis. Writing your own implementation doesn't do anything to help you there.
Nick Craver
Wow, interesting. What language did you write it on?
NullUserException
@Nick - I used to be more ego-centric but that is simply not the case here. Three of the four conditions are actually implementation-agnostic. I am simply trying to get across the fact that there is no magic bullet to mastering any specific language.
ChaosPandion
@NullUserException - I originally wrote it all in C# but now I am rewriting the compiler portion in F#. (It is a lot of fun!)
ChaosPandion
This would have been a good answer if it had been worded more nicely. I too had to write a JS interpreter for a course project, but it was more of a task of understanding the language than actually implementing it. You don't need to actually implement the language, just reading the ECMAScript spec will give you an excellent understanding of how the language works.
casablanca
@casablanca - I certainly can't say you are wrong.
ChaosPandion
This is a good answer, regardless of what you think of the author's ego. Implementing a language and writing lots of code in a language are the two best ways to truly master it. I guarantee you John Resig didn't attain his level of skill by reading a book.
Chuck
The OP asked about 4 things, only 2 of which this answer addresses. There is nothing you can learn about the DOM nor event-driven programming by implementing JavaScript yourself. This is only a half-answer.
Roatin Marth
+1 I get your point and I fully agree. Being able to implement it gives you instant "master" status. As far as mastering cross-browser problems... I have been through all of that crap in the last ten years, and I don't think it makes me a master *at all*. Frankly, it makes me cringe! Cross-browser differences are spawn of the devil, and mastering them is a thing of the past. Besides, masters don't focus on the bad parts, they focus on the good parts.
Josh Stodola
@Roatin - OK, so this isn't a perfect answer as the votes suggest but the core idea is sound. "To master a language (or API) you have to use it a lot."
ChaosPandion
A: 

There's no substitute for experience, but when I have something specific I need I usually visit the Mozilla Developer Network or the Opera Dev Centre

Gareth
+1  A: 

Hi,

maybe you're interested in the standards, defined by the TC39 Committee:

https://developer.mozilla.org/en/JavaScript_Language_Resources

Edit:

This maybe a little bit more advanced than just Basic JS but it's a really good resource about design patterns in JavaScript.

http://ajaxpatterns.org/Patterns

sled
I guess this would help if I were to implement the language, but not as much for day-to-day coding.
NullUserException
I think it's good to understand language specific subjects like how anonymous functions are implemented etc. Another thing you could have a look at are design patterns in general especially connected to event-driven programming :)
sled
+8  A: 

If you master Javascript, you can explain what the following code means:

Function.prototype.bind = function(){ 
  var fn = this, args = Array.prototype.slice.call(arguments), object = args.shift(); 
  return function(){ 
    return fn.apply(object, 
      args.concat(Array.prototype.slice.call(arguments))); 
  }; 
};

And if you can't explain what it does, you should definitely read this great tutorial of John Resig: Learning Advanced Javascript, which makes you truly master Javascript!


The example above includes a lot of advanced stuff, like:

  • Prototyping
  • Closures
  • arguments
  • What is this?
  • Using standard Javascript Objects ( Function, Array )
  • "Advanced" methods ( Function.apply(), Function.call() )
Harmen
Nice link - I'd also recommend the Secrets of the JavaScript Ninja book too - http://www.manning.com/resig/
Russ Cam
@Harmen very nice link indeed. +1
chelmertz
+4  A: 

My best advice to better understand and learn the language is to look through the source code of the popular libraries such as jQuery, Prototype, ExtJS, YUI, base2, glow (maybe not so popular at the moment, but worth looking at nonetheless).

You'll see

  • a mix of functional and object oriented programming practices
  • a multitude of closures
  • exactly how the different browser event models are abstracted away

This will provide a wealth of insight into how the language has been used in libraries that are used in countless commercial applications. Reading the comments can prove insightful and often have links to blogs or bug tickets such that one can gain a deeper understanding of the issue.

Russ Cam
+14  A: 

You have to accept it for what it is. Best resource: the book "JavaScript: The Good Parts" by Douglas Crockford, published by O'Reilly and Yahoo! Press.

JavaScript is an Object Oriented language, but not in a way familiar to Java and C++ programmers. Objects are prototype-based, not class-based. JavaScript is also a functional language, not quite to the extent that LISP is, but much more so than most languages in that functions are truly first-class objects.

Learning JavaScript after knowing only Java or C++ is like switching to the pipe organ after playing piano all your life. You already have the skills you need to develop the additional skills you need to master it, but it's not a piano and no matter how much you complain, it does NOT have a damper pedal.

Mark Lutton
+1 For the piano analogy; it's kinda like what it feels now. Trying to bend the language into something I am familiar with
NullUserException
You can't bend a pipe organ into a piano. Using functions as first-class objects is as much a part of JavaScript as playing bass lines on the pedals is proper pipe organ technique. As for inconsistent behavior across browsers, that's nothing compared to pipe organs. No two are alike, and you can't even bring your own to the concert hall.
Mark Lutton
If you don't want to go out and get the book, or even if you do, check out this video too: http://www.youtube.com/watch?v=hQVTIJBZook
MatrixFrog
I'm sure, like many JS developers, Crockfords video, then his book completely changed my opinion of the language, and made something that had up until then been a chore, become the core of the work I do.
Matt
Very nice analogy between a piano and an organ, my musicological hearts starts beating again…
Marcel Korpel
Damper pedals are for romantics! There's no room for that wishy-washy crap in programming. You hold the key for the duration of the note, dammit. Spend your days learning Javascript, and your nights banging out 6 part Bach fugues, and you will be on your way to being a ninja at life.
MooGoo
A: 

There are at least a dozen good videos on Yahoo Theater that do a good job of explaining javascript, basic and advanced, and DOM and the like, without skipping on the details and nuances.

Also -- while you might hate this, the proof that God does not exist is undefined.

Marco Mariani
+1  A: 

Although you could learn Javascript from example code, Javascript is probably best learned from a master because it's full of traps. That's why "JavaScript: The Good Parts" is probably where you should start.

Here's a quote from the author:

When I was a young journeyman programmer, I would learn about every feature of the languages I was using, and I would attempt to use all of those features when I wrote. ...

Eventually I figured out that some of those features were more trouble than they were worth. Some of them were poorly specified, and so were more likely to cause portability problems. Some resulted in code that was difficult to read or modify. Some induced me to write in a manner that was too tricky and error-prone. And some of those features were design errors. Sometimes language designers make mistakes.

Most programming languages contain good parts and bad parts. I discovered that I could be a better programmer by using only the good parts and avoiding the bad parts. After all, how can you build something good out of bad parts?

Dale
A: 

Hi, the concept of event-driven programming is really simple. In the classical program, the line of code must be executed one by one, from the beginning to the end. The program control the execution and ask the user to make some choices. But whatever the user do, he must follow the program sequence.

In event-driven programming, the user is the one that control the sequence of execution. The program do nothing until the user interact by clicking on certain button, moving the mouse or just selecting a menu. So the execution will depend on what the user do on the graphical user interface (GUI). For exemple, clicking on a button "Delete" will probably call a corresponding function that may act differently depending what is selected.

I hope that it give you an hint!

Zonata
+6  A: 

Inconsistent behavior across browsers

This is really important to keep in mind, javascript is 'nearly' equal in ALL browser and differences are usually in the obscure areas. Where most browser inconsistency is perceived however is not in JavaScript but in the DOM API. JavaScript has a bad rep mainly due to poor/incomplete or even outright different DOM implementations.

Event driven programming:

Event driven programming is a means to accomplish loose coupling (next to dependency injection), an object fires events to whomever is interrested and other programs can listen and act on the events. More then one listener can for example listen and act on a click event, but the click itself is not dependant on it's listeners.

Behavior of anonymous functions

Anonymous functions are no different from named functions, and are used in cases where you simply do not need to store a reference to a piece of code. They are ideal for self executing code, callbacks and oneshot listeners. They should be avoided inside loops and when using them inside recursive functions a good 'thinking it through' is needed.

The keyword this

Global functions can be considered 'methods' of the global scope (window) and this is a reference to the scope of a method. Where this is concerned, one needs to really make the distinction between function and method. In other languages, this is usually a safeguard, but in JavaScript, this is mandatory when a referencing properties and methods on the current scope of a method (except for methods and properties in the global scope).

Advice

Lots of awnser already listed the good books and YUI theater movies, they are all worth reading/watching, but the real school is get your hands dirty, so I'll give you an assignment:

  • Write an EventDispatcher/Observer/Publisher (same thing, different names/apis) that can:
    • fire any event
    • invokes the listener function on the scope of itself
    • passes an eventObject to each listener function
    • invokes each listener in the order they started listening
    • can remove specific listeners per eventType
    • can be instantiated so each instance has it's own events and listener stack.

Doing this basically teaches you about your last 3 points and gives you a useful reusable pattern. You can cheat ofcourse and look one up, but try to understand it's workings and how you would use it in your programs at the very least ;)

I would also advice reading about design patterns which are useful in any language, including JavaScript. This will simply make you a better programmer period.

How I mastered javascript

1.) I wrote my own DOM framework (you learn a LOT from this)
2.) I wrote my own Class implementation (starting to learn about structure)
3.) I wrote my own ScriptDependency loader
4.) I read a lot of discussions and follow a bunchload of blogs/twitters
5.) Bought/read the books, watched the YUI theater vids
6.) I awnser questions on Stackoverflow (sometimes I learn a bit more from this STILL)

Writing code and more importantly REwriting code whilst always questioning myself was in my case the best learning school. Fortunatly I began in a period where jQuery didn't even exist and making your own toolkits was a must. Frameworks and toolkits are helpful, but only teach you how to use their API's, they don't teach you much about JavaScript in depth.

BGerrissen
+1 on the DOM framework, and I would note that I would expect a lot more wonkiness with the new HTML5 set of object related features.
altCognito
+1  A: 

Watch as many videos you can by Douglas Crockford

Don
Do so as long as you do not take the guys words as gospel. Hear what he has to say, then learn for yourself why some of it is plain wrong.
MooGoo
... or a waste of effort when you could be doing something productive.
altCognito
I have actually met this guy. He gave a presentation on JS at my school.
NullUserException
A: 

One of the ways I learned is by writing Userscripts (Greasemonkey). It's not that difficult to develop your own JavaScript application. It's much more difficult to design JavaScript AROUND someone else's website. You have to deal with their design and implementation choices. It has really helped with closures, anonymous functions, scope, this, etc. I did a lot of it with jQuery, as well. However, if I was just learning, I would start with native JavaScript.

SimpleCoder
+1  A: 

You don't learn from reading. You learn from doing. Doing over-and-over correctly is the best way to master.

How do you know it's correct?

  • Start by learning from reputable sources: yahoo, google api/coders, good books
  • Get verification from the JavaScript coding community

Use it over and over again and keep up-to-date with new changes with the different browsers.

vol7ron