Grow your CSS skills. Land your dream job.

The JavaScript “Ah ha!” Moment

Published by Chris Coyier

A number of years ago we talked about The CSS "Ah ha!" Moment. That is, the moment in which you learned something about CSS that made it click for you and had the feeling of understanding wash over you. For CSS, mine was realizing that every element on the page was a rectangular box that lay themselves out in a particular manner and that I could affect the size, position and contents of those boxes.

Let's do it again, only for JavaScript! If you feel like you have a decent understanding of JavaScript, what was your "Ah ha!" moment? Or are you still waiting for it?

For me, I had never written a line of JavaScript in my life but I picked up the book Learning jQuery and started reading it on a flight. I had the moment when I realized jQuery was essentially a "find something, do something" library. I already knew CSS, and jQuery used CSS selectors for the "find something" part. "Do something" in jQuery can be as simple as "click", "hide", "show", "slideToggle", etc. Even I can do that, I thought, and I rushed to my hotel room and started playing.

Comments

  1. Hector
    Permalink to comment#

    For me that moment was when I realized that everything was an object.

    • Fernando
      Permalink to comment#

      Me too! Think like object change everything!

    • Chalk up one more for everything is an object. This also kind of went hand in hand with a DOM “ah ha!” later that day for very similar reasons.

    • me too! i was totally stunned about that! :D

    • Patrick Laughlin
      Permalink to comment#

      Could someone elaborate on this? I’ve heard this before as being really important but still don’t quite understand. Thanks!

    • Thanks @Charlie for your response. Indeed time is money and make no sense to go back in time to learn deprecated API when the entire world is looking forward to be ultra productive.

      When I was a kid I destroyed all my toys looking for the reasons of how they worked; and in the same way it makes me feel sad how many people uses jQuery every day without a real under of what is going on behind the scene.

      Do you know as @ezekiel stated JS is (in it own way) a 100% Object Oriented by itself? I wrote a thesis only with that research! Feel free to take a look at the website, http://lab.pragres.com/sweb/ located yet in the labs of my company.

    • One more vote for everything is an object. Everything very simple after learning that.

    • Permalink to comment#

      Realizing what ‘objects’ are helped me with ALL my programming. PHP has benefitted immensely, for example.

    • Permalink to comment#

      My Aha-moment with javascript is yet to come, but I sure had one when I read that Salvi guy‘s comment! :)

    • Its an object! Then suddenly it was all clear

    • Permalink to comment#

      Definitely the “it’s an object!” moment. Totally changed how I write Javascript.

    • Michael Chang
      Permalink to comment#

      I SO wish Javascript were object-oriented. Javascript, while object-based, is prototype-oriented. Now that doesn’t mean that you can’t do things with the language that make it *appear* object-oriented. You can. But it’s not part of the language syntax.

    • Brian
      Permalink to comment#

      1 more for this

    • But javascript is object oriented. It’s just not classical. Saying it’s not object oriented because there’s no classes is like saying there’s no variables just because there’s no strict typing.

    • Everything is an object :)

    • Permalink to comment#

      If you like that approach you should try Ruby.
      Numbers, code blocks, classes, and basically everything is an object.
      To be paradoxical, the Class of the Class object is itself.

  2. Micah
    Permalink to comment#

    My javascript Ah-ha! moment was when I realized how similar it was to PHP. Set up variables, set up functions, grab from the dom, process, output…that’s about it.

    • Me too! WOOT! go PHP!!!

    • Abel
      Permalink to comment#

      I think you will soon have an “Ah-ha” moment when you realize javascript and PHP are actually not similar. Client-side vs server-side… the only thing similar about them is that they are both programming languages.

  3. Mine was JavaScript closures. After blowing it on an interview. I knew I really had to get my head wrapped around closures. So if I may impart unto all here, this is my take on closures and I hope it helps:

    As I understand it, at a basic level, a closure is a returned function that encapsulates (not references) variables/values from the parent function that returned it. I hope my explanation is right and, if so I hope it helps someone here.

    • A closure is the set of local variables that are kept alive after a function call* has completed, because those variables may still be required by a local function, and a reference to a local function has somehow been exported during the function call.

      The local function can be returned by the enclosing function, that’s one way of exporting its reference, but there are other common ways too, the local function can be attached to an event, pushed onto an array, anything to prevent it from being dereferenced once the enclosing function has completed.

      * doesn’t have to be functions, it can be any execution context, but let’s just leave it at function calls for now, shall we?

      A closure is effectively all the stuff that belongs to an expired execution context that cannot yet be discarded because there are still references to it.

      I can’t say I can describe getting closures as a JavaScript a-ha moment though, it was a separate a-ha moment altogether, beyond JavaScript. I mean, you can ‘get’ JavaScript a long time before getting closures, they’re pretty advanced.

      Most people discover closures completely by accident, do a bit of reading, and then start using them by design, still without fully getting them. Which makes it such a tricky interview question, because it’s the kind of thing people can use without really being able to explain. (And there are many difficult to read tutorials on the topic, which doesn’t help.)

    • Now you have me wondering what kind of interview you can blow just by not understanding closures. They sound extremely important to advanced JavaScript understanding, but I’m a little surprised that you can blow an interview by not understanding them.

    • It was closures and then some. Really advanced JS role I was applying for.

    • Permalink to comment#

      @Lee Kowalkowski: A-haaa!! (well, here it is :D )

    • Closures, I know what they are but reading a written explanation still confuses me. Stoyan Stefanov draws you a diagram. I looked at that and the light in my head went on. It’s a brilliant book.

      Object Oriented Javascript by Stoyan Stefanov.

  4. Permalink to comment#

    Hmmm, most recently, a minor aha moment that I had was realizing how very little of the javascript that I work with should operate before DomReady. And the only way to do a great domready cross-browser is with something that has been tested, like jQuery’s domready functions, or the DomReady library that was taken out of jQuery.

    Essentially a realization that before jQuery, I was probably doing it all wrong anyway.

    • Permalink to comment#

      Err, I meant to say that even .hide() or .show() need to be wrapped in domready. Sooooooooooooooooooooooo ….damn near everything except function declarations.

      Long live jQuery.

  5. Havvy
    Permalink to comment#

    1. Everything is an object.
    2. Closures.
    3. Functions can be stored and passed around.

    • Seconded. Once you can wrap your mind around these three things, you can go from “doing things with javascript” to “creating things with javascript”.

    • same above three as well for me. Also ‘anonymous’ functions. One can just pass the entire function body to another function.

  6. Permalink to comment#

    Much the same as hector. My aha! moment is when I started learning to create objects in vanilla javascript. It really makes things click when you come to understand that a method is just a function inside of a function.My second aha! was when I started understanding that everything is an object.

  7. It’s funny that you post this because last night while I was re-designing my site I Googled jQuery to learn more about it. I’m now (6hours later) understanding a lot of it. So I guess my ah-ha moment would be when I realized that jQuery & JavaScript have so much potential and like metioned above, it’s just a object orientated language. I always got scared seeing it used on your site, now I’m ready!

  8. Permalink to comment#

    Actually, jquery is about “when something happens, find something, do something” because javascript is event-based.
    My Ah-ha! moment has yet to come, I guess xD

    • Gabriel
      Permalink to comment#

      Well, I disagree with your “JavaScript is event-based” statement…
      JavaScript is object oriented (prototype style) with some functional programming baked in.

      You can define how your document elements (objects) will behave when some event is triggered, but the event handlers are object properties… the DOM and browser window can trigger events, not the JS.

  9. fent
    Permalink to comment#

    I don’t remember ever having a javascript ah ha moment and I’ve been coding in it for several years. I think it’s because javascript is so lenient and functional it lets the programmers express themselves in a way that’s already familiar to them.

  10. nelson
    Permalink to comment#

    mine was when I found that every operation returns a value.

  11. Charlie Magee
    Permalink to comment#

    I was trying to create some sequential animations and everything kept running at once. I found an example out there in the vast interwebs that nested a function inside a function. My elements started moving the way I wanted them to and I was off and running. Everything started being fun after that.

  12. Alexei Martchenko
    Permalink to comment#

    I started playing with JS in its early years in netscape, and everything was kinda fuzzy at that time, but my A-HA moment was when I discovered the relationship between DOM and JS Objects and you could access parents and siblings via methods. Basically it was a double-a-ha for me since the DOM idea clicked for me aswell.

    Come on guys that was 1998 or something :-)

  13. A few years back when I first started doing ajax requests by hand (not jQuery at the time). Until then everything I wrote was simply procedural/functional code, and I didn’t worry about event based or object-oriented patterns. This was also when I started learning how to avoid the old inline onClick='doEvent()' and start using unobtrusive JavaScript.

  14. I was looking into JavaScript on http://javascript.crockford.com/ and then come to know about the concept of lambda functions and closures. It was mind-blowing.

    All the thanks to Mr. Crockford

  15. Permalink to comment#

    Like many others, understanding closures was when it all somehow clicked together. And even after I thought I knew javascript, reading Stoyan Stefanov’s “JavaScript Patterns” was full of small ah ha! moments.

    • erick
      Permalink to comment#

      I second Stoyan’s book “Javascript Patterns”!!
      So many ah ha moments in that book that it’s essential for higher level javascript !
      Well worth the price and goes a long way!

  16. Jonas
    Permalink to comment#

    Im just at the beginning of JavaScripts possibilities, but my recent JS AHA moment was, when I understood the concept of passing arguments to functions and the general use of OOP :-)

  17. Well, coming from the ActionScript world (don’t hate) what clicked for me was that DOM Elements are like MovieClips

  18. I had three major ah-ha moments in the various stages of expertise:

    1. Before learning Javascript, code was always executed immediately and the only halting was done through user prompts. My first “ah ha” moment came when I realized code could be encapsulated in functions and attached to certain events.

    2. My second “ah ha” moment came when I was able to separate the idea of Javascript from the DOM. DOM manipulation is just one use of Javascript, but it is not Javascript itself.

    3. Finally, and more recently, the Douglas Crockford Yahoo videos have added a significant depth to my understanding. The mysterious things that jQuery and other libraries did finally made sense when I managed to grock the prototype chain and look at all data and functions as objects.

  19. The big moment for me was when I learned about the module pattern for creating objects in JS. That was my first taste of object-oriented JS, and changed my code from a pile of functions to a structured web application.

    • I agree. Using design patterns was the eureka moment for me. They are a lot more vital to well written JavaScript than they are to PHP. The book that opened the door to me was Pro JavaScript Design Patterns by Dustin Diaz and Ross Harmes.

    • Module pattern, yes! I think it has changed my view of javascript.

    • Another vote for the module pattern here… however, I find myself using the revealing module pattern most of the time, to be specific.

  20. I am no JavaScript master.. tbh I am not really sure what closures are… though I may use them. I had two ah-ha’s so far.

    1. Javascript is prototypal.. that word didn’t make sense to me until I realised it meant “almost object oriented”.
    2. A lot of JavaScript directly targets the DOM. Before jQuery was around, or at least common, I had only used it for timers and the like. But libraries have made a lot of people do more things with the DOM than they would before.

  21. You had a jQuery ah-hah moment. The JS one is yet to come. I agree with a lot of people here: everything is an object, closures and when it comes to browser interaction (which jQuery makes very easy and very CSS-ish) event delegation is when I started to go YES!

  22. Permalink to comment#

    I have a JavaScript “AHA!” moment every time I use it. It’s the same each time. It’s:

    “Aha! I don’t know diddly-squat about this language!”

    :)

    (In other words, I probably learn something about JavaScript each and every time I use it.)

    • That’s true for myself as well. And one thing is sure “Aha” moments are sweetness sent from the gods. ;)

      That’s one of the reasons I built http://www.tiljs.com/, to share my JavaScript “Aha” moments and learn from other people’s “Aha” moments. And I believe we can agree that JavaScript has a lot of tricks and gotchas that can trigger an “Aha” moment. :)

  23. My AhHa was after working in Javascript for years, trying to look at the JQuery code and figure out what was going on. I realized (and probably already knew) that I only know about .05% of what I wished I knew in JavaScript. There are some truly talented and genius developers out there and I thank them for their hard work in helping to shape the web.

    Really though, some AhHa’s would have to be when I read how to modify styles through Javascript in JQuery, and upon reading how Pinterest did their Pin repositioning using javascript and math.

  24. Mine was when I found out that “$” was the name of the jQuery function and you were just passing parameters to it and it was doing all of the hard work to find those elements/objects. For the longest time I was using jQuery not really knowing what it was doing (yes I learned jQuery before JS).

    • Joaozito Polo
      Permalink to comment#

      yes! the $ compreension is a cool sample of ah-ha moment!

  25. Still waiting for my ah-ha moment…

    • Joaozito Polo
      Permalink to comment#

      Jamie, read “jquery types” article… after this, your ah-ha moment will come…

  26. Schmotty
    Permalink to comment#

    Mine was when I had to make a flash menu that used a mysql database on a magento ecommerce site. I was very much learning actionScript, javaScript, php, and mysql all at the same time. I used php to list the menu items in a js variable that I then read through actionScript’s externalInterface class.

    The moment I got the ‘ah ha’ was when I finished and realized I could have made things much simpler without Flash.

  27. We all love the mighty jQuery, but those who never struggled with plain JS API, and learned how and WHY the client server scripts works, those in my perception have less possibilities to face a real, challenging Web programming environment.

    I had been working for more than 3 years with jQuery so far (and other three years without it), and I a lot of times I needed to load something with the my old document.getElementById() friend or parse an XML with a classic for, or create a CVS file reading for my old fiend the classic array.

    Summary: In order to fully understand jQuery and hence be able to fight vs. any jQuery uncovered situation (they are many, even if they are hard to find) it is a must to have an strong JS background.

    So… who is with me ? :-)

    • Charlie Magee
      Permalink to comment#

      That’s a very good point Salvi. It’s a bit like wanting to slam dunk without learning how to dribble. Fundamentals first, play of the day later.

      However, I’ve got so much to do and so little time. Most of us have to start where we are and get moving. I’m gonna stick with Coffeescript and jQuery and follow along from there. I simply don’t have the time to get to the fundamentals on Javascript. If I ever build something that backs me into one of the corners you describe, I’ll pay you a bunch of money to bail me out.

    • Charlie,

      I used to say the same thing. I was stronger in jQuery, weak in natural JavaScript. For the longest time I was very able to code in jQuery and achieved desired results, but I also never really understood why they worked that way. I was then thrown into an envinronment that was chaotic jQuery and old school properly written javascript with objects, functions, loops, and the like. Let me tell you, I went from feeling like a savant to feeling like a monkey scratching his head.

      I think it’s also a misconception that jquery “saves people so much time”. To a degree, and for certain things, yes, but doing some things in standard JavaScript is actually faster, both coding wise and performance wise.

      Anyway, my point is don’t be so quick to dismiss fundamental JavaScript. You might be surprised when you need it.

      Also, if you don’t understand the fundamentals of JavaScript, you’re probably writing code thats horribly formatted & performs badly as well.

      Putting a bandaid on a flat tire might get you home, but it won’t get you to Canada.

  28. When I realize that almost everything is an object, and what is not, at least can behave like, and of course ‘closures’, once you get it, you can feel like you really know the language.

    Also I think I noticed too late that javascript has functional scope, I would have liked to know that since the beginning :S

  29. Just what the f**k “this” was referring to…

    • Permalink to comment#

      Love this one. I have had this realization twice in the past two weeks.

      1. If you call setTimeout, this now references window. so inside a function you have to do this:
      function someFun(){
      var newThis = this;
      setTimeout(function(){
      alert(newThis);
      }, 100);
      }

      The interesting thing is that the scope of the inner function is global but you can reference a local variable from inside the function. Weird??

      2. I recently started working with Backbone/Underscore and this changes all the time and you really have to follow your scope

  30. Gaurav R
    Permalink to comment#

    My aha moment was when I unknowingly used closures in a process of finding solution to a problem. I was glad that I finally had a bit understanding of it after struggling for a long time. And also some aha moments while reading Stefanov’s OO Javascript .. Awesome book it is.

  31. Permalink to comment#

    http://tiljs.com – nice feed

    i’m working on a similar thing but all html related

  32. First off, I have to say – long time reader/lurker here but I just have to give kudos to you, Chris. Your posts are always on the leading edge of what’s new and fresh and I can not tell you how much I learn from CSS Tricks. So for that I want to thank you – a million times over.

    As for the question: …when I realize I haven’t missed any semicolons and everything works as I intended.

  33. Leo V
    Permalink to comment#

    Still waiting for it, I’m a newbie to jQuery and JS… can someone show me a path to rabbit hole?

    • You should go take a look at Jeremy Keith’s book on Javascript, its called – “DOM Scripting – Web Design with javascript and the Document Object Model”. I’m currently going through it and so far its taught me a lot! (I’m a beginner with js too)

    • Darren
      Permalink to comment#

      Check out Nettuts “30 days to learn jQuery course” you’ll get a good start with that, then some of the other blogs will begin to make a little more sense, until you have your lightbulb moment and then they’ll all make sense.

  34. Permalink to comment#

    That when you create a new object, you (more or less) are creating a copy of its prototype.

  35. My “aha” moment has been comprised of several small ones. The biggest of those was the concept of creating classes in Javascript.

    ex.

    var className = function(){
        this.variable = ...
    }
    • steve
      Permalink to comment#

      Your comment is an a-ha moment. I originally thought it was when I accessed the prototype of my own custom object of arrays. but this opens a new door for manipulating DOM that hadn’t considered.

  36. for me the biggest “ah ha” moment when I realize I can use console.log(something) instead of alert(something) and check it in the console, the moment I’m most frustrated is now over.

    2nd one is how $(this) is different than ‘this’, sometimes I’m just confused about it and have to console.log(this) to make sure I’m on the right path.

    3rd one probably is the operation with js, I didn’t realize that 1 + 1 can be 11 (as a string type ) in JS instead of 2 ( as a number)… for me that’s one of the coolest ah ha moment.

    But this doesn’t mean my “Ah-ha” stops, I think I probably will have many more “ah ha” moments while working with js / jquery in the new upcoming projects, that feeling of realizing something you should have is so special and I can’t wait to have it again

    • Mladen
      Permalink to comment#

      The moment I learned that strings like “2.13″ can be converted to number by adding + in front of it.

  37. For me it was scope / closures. It is the most common mistake for new comers.

    @Leo V – I have written a blog post introducing the basics of JavaScript from a .Net developers point of view. It may help you get started. Getting Started With JavaScript

  38. Permalink to comment#

    When I realized that you can call ‘new’ on a function to use it as a constructor for a new object.

  39. For me it was when taking this course just recently

    http://tutsplus.com/course/30-days-to-learn-jquery/

  40. Permalink to comment#

    My moment came when I realized that I could use JavaScript as a steroid for CSS: I could add/remove classes and styles dynamically in ways that I couldn’t otherwise do.

    It’s weird though, the more I learn about JS the more aha moments I think I have left to unlock.

  41. My three biggest A-HA moments were:
    1. Realizing just how malleable/flexible/powerful the combination of 1st class functions, prototypal inheritance and closures makes JavaScript.
    2. When I decided to write a standalone version of a library that I’d originally written with a heavy jQuery dependency by writing my own ultra-minimal version jQuery, which lead me to read the source code of jQuery, Zepto and Underscore to see how they did their “magic”.
    3.Writing code for node.js.

  42. Anthoni Caldwell
    Permalink to comment#

    My moment was when I made a texted based roleplaying game in raw javascript. I used js fake classes to make entities in the engine, with functions in the class member functions. It made making the game a lot easier.

  43. I don’t know a lot of plain JavaScript right now, but lately I’ve been having a huge jQuery “ah hah” moment. It’s all thanks to watching the net tuts “30 days to learn jQuery” course. I’m stalled on lessons 9 and 10 of 30, but that’s mostly because those lessons are having such a huge impact on me. I’ve been writing jQuery for years now, and was hired at my current job largely because I know a lot about jQuery, but what these lessons have shown me has got me completely re-thinking the way I write jQuery.

    My “ah hah!” moment has been that I can actually structure my jQuery cleanly. Saying that now, it sounds kind of obvious, but it’s having a huge impact on my code. In addition, I’ve learned a few structuring tips (mostly from the aforementioned course) which are contributing to much cleaner code on my part. I’m now caching any jQuery call I need to do more than once, rethinking the way I structure everything I do in jQuery, using functions and object oriented coding more, scoping my variables, using more control over “this”, and defining variables in comma separated lists. Overall, the result is that I’m writing about 1/4th the code in a lot of places, and am finding elements about 1/6th as often.

    In addition, I’ve just begun writing my first tiny jQuery plugins. When something needs to be done over and over, sometimes I write a tiny jQuery plugin instead of a function to take advantage of jQuery. I’m beginning to understand what it means to extend jQuery and modify the way things from jQuery work, and I finally understand how to use $.extend() to define defaults and then override them.

    All of this is taking my code to an entirely new place, with better human readability, faster execution, and much cleaner, leaner code.

  44. My ah ha moment recently was realising how little javascript I actually know! And realising it’s important for me to learn the basics as well as knowing how to do a bit of cool stuff with jquery.

    Another ah ha moment was realising about reusing and passing things to functions, and at the same time realising how way too long and messy my code had been :D but overall realising how many more ahha moments I have to come as I learn and improve :)

  45. I learned JS with jQuery as an entrypoint. A big step for me was learning how to use events and realizing that events can be triggered manually. Understanding OO in JS was also a big step.

  46. Permalink to comment#

    When I realized that I could use the Firebug/Chrome/IE console to quickly test any code or functions.

    - If I don’t remember how that function works, I test it in the console.
    - If I’m not sure about the syntax, I test it on the console.
    - If I don’t know if this piece of code is going to work, I test it on the console.

    ;)

  47. Siggi
    Permalink to comment#

    … when i found out, that “Everything is a Object” is only half of the truth.

    - the interpreter is one big, event-based eval-loop and from his point everything is a function.
    inside JS, “eval is evil” , but var f = new Function () { ... }; is FTW,
    the same with var obj = new function() { ... }

    • Havvy
      Permalink to comment#

      ‘new Function () { … }’ doesn’t work. It’d be ‘new Function (” …”)’, but that is just an alias for eval. You have all the problems with new Function as you do with eval. But you can make eval-free functions that do what you want pretty readily:

      
      /**
       * Requires ES5 due to arguments (array-like object) object instead
       * of actual array.
       * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply
       * @param context Object to wrap.
       * @param method {String} Name of method to wrap.
      **/
      var wrapMethod = function(context, method) {
        return function () {
          context[method].apply(context, arguments);
        }
      }
      

      (Indentation doesn’t seem to be preserved…)

      The other one is an interesting way to use a one-time constructor that I haven’t seen before. I’m going to add that to my list of useful patterns.

    • Siggi
      Permalink to comment#

      @Havvy: yes, your’e right. it should be new Function ("..."). sorry for that.

      but its far more than an alias for eval().
      eval() instantiates and executes in one step with no or little chance to prevent bad things to happen.

      with an encapsulated try/catch inside the “create Function”-block you can verify the new function before returning it to the calling context.
      invoking or binding it to a new context is a totally different step :-)

      the var obj = new function() {...}-constructor works nearly the same as a closure or immediately invoked function, but has some advantages (at least in my opinion).
      it allows private vars and functions inside the created object like the others,
      but accessing vars from its calling scope is way more predictable (the same with this)
      this comes in handy when doing crazy stuff like nesting this type of constructor and still having access to its base-calling scope’s vars.
      this way, you can have private, class-shared, protected and public (from the base-class-point-of-view) vars the easy way.

      but that’s far beyond clickety-find-do-DOM-stuff . . .

  48. Permalink to comment#

    I had quite a few “a-ha!” moments with js, but one of the biggest was understanding PHP hooks, which are basically very similar to js callbacks.

  49. Permalink to comment#

    My a-ha moment was when i realized that I can do object oriented javascript apps. This gave me a lot of more oppurtinities to look at the power of javascript. The more you dive deeper in it the more you want to experience.

  50. Permalink to comment#

    My javascript Ah-ha! moment was when I realized how scopes are working.

  51. Mine was when I realized that HTML elements were just that (elements) and that jQuery could find and affect these elements however I want. As said above, “find this, do that”. Havent found many uses for Js beyond manipulating the DOM, but I’m sure it will pop up someday and I’ll have another ah-HA moment.

  52. bigbossSNK
    Permalink to comment#

    When Douglas Crockford called the trailing parentheses of an immediately invoked function ‘dog balls’

    http://t.co/hK3QZB5r

    • Ha ha ha! Hilarious!. I love how Douglas Crockford can present a dry topic like programming and interject just enough humor to keep the audience engaged.

    • I saw this presentation and I disagree with Mr Crockford here (and not only here).
      He says that the reason why he puts parenthesis outside the invocation is that the whole invocation is important, not just function.
      But these parenthesis are not there to show what is important there. They are there to ensure that this is function expression in contrast to function statement. Invocation is always an expression, so there is no need to enclose it with parenthesis, ergo showing that this is expression. It just messes in heads ;)

      So at the end explaining that situation like Mr Crockford did is not helping understanding what really is going on in this language.

  53. John
    Permalink to comment#

    For me the Javascript “Ah ha!” moment was just called JQuery. Even though it’s pretty wrong to call it that, cause knowing JQuery can make you think you can write Javascript, but that couldn’t be any further from the truth.

    JQuery just makes ir incredibly accessible by using the CSS selectors and convenience methods like slideUp/slideDown. Writing these in native Javascript would be a pain in the ass and most JQuery writers wouldn’t even know where to start.

    Of course, since JQuery is here to stay, this isn’t really an issue. As long as we’re not talking about Javascript performance (and mobile) that is.

  54. Permalink to comment#

    @bigbossSNK Hahaha, i laughed my balls of when i was watching this! #dogballs

  55. Chuck Norris
    Permalink to comment#

    Mine was the moment I came into existence.

  56. Permalink to comment#

    This is exactly what I explain everytime people ask me how I learned web design! It’s that one moment where you suddenly see how it all works, and then everything becomes so much easier. I acctually learned most of the coding myself, just googling simple things like how to fetch a query in php (which btw, was my aha moment), and then I just kinda knew the language after a while.

  57. Chandra
    Permalink to comment#

    I have read several articles about Closures, but I had hard time understanding the concept. Once I read, it’s just about returning a function to the global namespace, that was my ah ha! moment.

  58. moz
    Permalink to comment#

    When i realized javascript has nothing to do wuth java

  59. Permalink to comment#

    I think I have had a couple over the last couple of years, but the one I am looking most forward to is one that hasn’t happened yet – wrapping my head around MVC in Javascript.

    I have a project where most of my prior Ah-ha moments have shown up, so I am looking forward to spending some time rebuilding it using MVC concepts.

  60. For me that moment was when I came to know about automatic semicolon insertion:

    
    function myFunc()
    {
        return
        {
            name: 'sarfraz'
        };
    }
    
    var f = myFunc();
    console.log(f); // undefined
    

    Doughlas Crockford had rightly suggested to have starting curly brace on same line instead of new line:

    
    function myFunc() {
     return {
        name: 'sarfraz'
     };
    }
    
    var f = myFunc();
    console.log(f); // this works
    

    I started off with jQuery (http://sarfraznawaz.wordpress.com/2012/02/12/learning-javascript/) but ever since I have started looking JavaScript seriously, I have fallen in love with it and have seen more than one aha moments :)

    FYI, here are other places where automatic semi-colon insertion takes place:

    var statement
    empty statement
    expression statement
    do-while statement
    continue statement
    break statement
    throw statement

  61. george mauer
    Permalink to comment#

    scope in closures works exactly how you think it would work if you forget all the nonsense object oriented languages have pushed in your head. This also made me much better at c# as I really understood lambdas.

    $.extend

    the captain obvious post on making javascript functions that return other functions

    learning a smattering of prolog and coming to understand how with boolean type coercion && and || are close cousins of the semi colon.

    dom events bubble up

  62. Wow, I think I’ve forgotten my personal JS a-ha! moments, but I’ll try a few basics:

    1. DOM stuff (window, document, onclick etc), is not actually JavaScript, they’re things provided to JavaScript by the browser. That is where 99% of the cross-browser issues are with JavaScript, outside the DOM, it’s plain sailing in comparison as far as cross-browser compatability is concerned.

    2. In a browser, everything is in the window object, so:

    function helloWorld()
    {
      alert('Hello, world!');
    }

    Can be invoked by:

    helloWorld();

    or

    window.helloWorld();

    3. Dot notation is interchangeable with bracket notation, therefore you can also:

    window['helloWorld']();

    and therefore via a variable:

    var func = 'helloWorld';
    window[func]();

    4. ‘in’ is not just for in a for loop, you can also use it as a test:

    var myObject = {a: 1, b:2, c:3};
    alert('b' in myObject); // true

    5. || and && do not return true or false, they return the last evaluated operand.

    function helloWorld(name)
    {
      alert('Hello, ' + (name || 'world') + '!');
    }

    6. DOM collections are not array objects, (they’re not JavaScript remember?) also doing getElementsBy…() will return you a live collection. For example, when you reference .length it will evaluate the getElementsBy…() all over again to recalculate the length, so if you do the following, you will have an infinite loop:

    var divs = document.getElementsByTagName('div');
    for(var i = 0; i < divs.length; i++)
    {
      divs[i].appendChild(document.createElement('div'));
    }

    Pfft, that’s all I can think of right now, without getting too advanced.

  63. Permalink to comment#

    I’m a pretty hard-core software engineer…I’ve written safety-critical software for aircraft and submarines. And I’m still to have my JS ‘Aha!’ moment. But I know what it will be: it will be when I understand the damn scoping rules.

    I guess I’m just not used to using such a loosely-typed and event-driven language and I don’t get what’s in and out of scope , especially when you’re passing functions around as data to events.

    I’ve also stayed away from writing big apps in JavaScript so have never had an excuse to dig in to the finer details of scope and closures.

    One day.

    • I prefer my submarine software writers use something a little more ‘better’ and leak proof.
      :)

  64. I think you just gave me mine when you described it as : a
    “find something, do something” library

    Thanks! (I’ll probably still let someone else write it though, I like CSS just fine. )

  65. Dave
    Permalink to comment#

    When I realised that it was actually a real, formal and complex language rather than the nasty little scripting thing that ran in browser clients (which how I had thought of it for the first few years of being a web dev)

    for me it was that JS was:

    prototypical
    event based (which was great with ..
    had closures

    that finally gave me the AHA

  66. Andrew
    Permalink to comment#

    Mine was when I learned that Ctrl F5 refreshes javascript in a browser. Sure it was long ago.

  67. My “aha moment” in javascript was when i realized that all in javascript is objects (i know it sounds silly…), like CSS many boxes with smaller boxes inside…
    jQuery is WOW library just because, it helps developers to develop a new way of thinking about javascript. All the others features are great but there are not the unique characteristic which made it WOW!!!

  68. Permalink to comment#

    A month or two ago, until then I just stumbled through it.

    It’s gone, html -> css -> php -> Javascript -> Jquery

  69. Permalink to comment#

    I think I’m close to the “Ah ha” moment, but still thumbing through and customizing open-source for now. I love jQuery!

  70. functional/logic programming; clousures; objects, objects everywere.

  71. I love how javascript “Ah-ha” moments have a tendency to invalidate each other.

    “Ah-ha! That’s how you force it to do X instead of Y!”

    “Ah-ha! Y is actually way better than X!”

    I guess the biggest Ah-ha was watching the Crockford videos and realizing it’s not broken, it’s just not conventional, and if you’re fighting the language then there’s probably a better way of doing things.

  72. Permalink to comment#

    man, I just had that jquery book on a flight ah Ha moment last weekend! awesome feeling. don’t know why I was so hesitant to start learning it…

  73. I really really liked it when I saw my own function just like JS built-in ones using the prototype property

    and I was really happy to know that i don’t have to install anything in my system to get JSON to work!! LOL

  74. For me, it was reading:
    DOM Scripting: Web Design with JavaScript and the Document Object Model
    by Jeremy Keith

    I still recommend this book to anyone who’s just getting started with Javascript.

    • Seconded – a great book for getting started, and Jeremy has an awesome way of making things easy to understand especially if you’re more from a design background :)

  75. Permalink to comment#

    Kind of different “a-ha!” moments at different stages. My first was very much like Chris’s, except that rather than reading a book, I was blindly using a plugin that didn’t quite do what I wanted. I decided to look at the code, and since it was jQuery (which used CSS-like selectors) it was pretty intuitive. All I needed to do was change where the plugin was expecting a certain ID to expect a particular class, and it worked. I could change what was being found, and I could make different things happen with it. A-ha!

    Almost around the same time, it became clear how to pass values and objects around. For a few days, I honestly thought when I was seeing a function like function(foo, bar) in sample code that there was some sort of significance to the ‘foo’ and the ‘bar’ and I had to figure out what valid values could go there. ;-) Didn’t take long to smack my forehead, but it threw me for a loop at first, not having any sort of development background at all.

    Other pieces of learning were incremental. Starting to fold in ‘vanilla’ JavaScript as I learned it and when appropriate (this.id vs $(this).attr(‘id’) for example), understanding how to trouble-shoot timing issues and resolve race conditions.

    And then while I was actually trying to solve another problem (application namespacing to avoid polluting the global namespace) I really finally understood objects. So that’s really the second “a-ha!” moment. Since then I’ve been in another incremental learning phase, but I’m sure another a-ha moment isn’t far behind.

  76. Scope.

  77. jsdev
    Permalink to comment#

    1) DOM
    2) Anonymous functions
    3) Coffeescript

  78. Sammy
    Permalink to comment#

    - anonymous functions
    - everything is an object
    - function scope
    - closures
    - self invoking functions

  79. Michael Mason
    Permalink to comment#

    Realising that it was all about the DOM, accessing it’s element and manipulating them in some way, whether it’s changing the appearance of something, adding an element to it or removing an element. From there everything is simplified to a question of working out the elements I want to work on, what their final state should be and what I want to do with them, and how to do it. Simples.

  80. Mine was understanding the use of ‘var’ keyword in javascript, variable hoisting, scope & prototypal inheritance.

  81. Rumpelrausch
    Permalink to comment#

    An ongoing chain of revelations:
    - sure the everything-is-an-object concept
    - short form of object declaration and instanciation by using brackets
    - breaking the same domain policy by using json/jsonp

    One favourite, though not a “now I understand” experience, was the fact that you can completely circumvent xmlhttp by re-using the src attribute of a known script object. Everything can be fetched from anywhere as long as you can encode it as js. Finally my feedreader webapp became possible. Currently reading this blog through it…

  82. Discovering that null, undefined, 0, false (of course) and “” are all false-y and:

    if (!foo) { // foo is falsey }

    is enough to test for a false-y variable! \o/

  83. Moshe
    Permalink to comment#

    my javascript ah-ha moment was jquery

  84. Permalink to comment#

    It was when I figured out how variable scopes worked in javascript. Like when you set a variable and then a closure, and then whenever that closure is called, it has access to that variable.

  85. nile
    Permalink to comment#

    when i realized that you could pass arguments into functions

    
    var funcName = function(funcArgument){
      alert(funcArgument);
    }
    

    </code.

  86. arnold
    Permalink to comment#

    when I realized that
    functions are also objects…..

  87. Same as you Chris, discovering jQuery and all it’s powers and capabilities. before that JS was a mistery, after that it became accessible. now I’m learning more and more “core” JS. :)

  88. Kushal
    Permalink to comment#

    The power if jQuery made me shout “Yay!” when I wanted to have my entire form div background color changed on focusing any of the inputs, and I was trying to do it with CSS (can’t happen) since I had more than one form in page. So then I used:

    $(this).parents().eq(3).css('background','#608CC4');

    since the div I wanted to apply color was 3rd parent of “this” input. Still I’m waiting for pure CSS solution to this.

  89. Still waiting for it. I still can’t quite wrap my head around the type of object-orientation that goes on in Javascript. I have no problem with Java, Python, PHP or even Lua-style OO, but JS just breaks my brain.

    • Ivaylo
      Permalink to comment#

      I felt absolutely the same until I read Stefanov’s book (I like Crockford but he always makes is sound as if there is some hidden genius in JS).

      My Aha there was that in JS object-orientation is kinda left left up to you. It is just an implementation thing which you can use to achieve OO-like effects. If you come from languages with pointers think of JS objects as structures which always come with three pointers: constructor, prototype and __proto__. Now, when creating new instances point these pointers different places and you get different type of “inheritance” like. A very powerful and flexible mechanism – no question about it – but so easy to mess up too. And all of this could be done without any of the native supposedly OO elements of the language. I love it how even for prototypal inheritance (which is supposed to be native in JS) Crockford always has a currently favorite way of implementing it – http://javascript.crockford.com/prototypal.html. Or the only other native OO thing there – the “new” operator being considered harmful by some – http://stackoverflow.com/questions/383402/is-javascript-s-new-keyword-considered-harmful? On the other hand partially this is what made beautiful things like jQuery possible…

  90. Understanding how information hiding can be achieved using function scopes.

  91. i found the importance of js and jquey while customizing iphonelu’s audio player and my daily routine adding onclick events for drop down menus on mobifreask’s free mobile website templates

  92. Permalink to comment#

    As others here have mentioned, for me it was watching and reading Crockford. When I read the history/background to the language it all made a lot more sense -I no longer felt frustrated and confused as I had been just by hacking at the language with a Java/C mindset.

    He explains: “JavaScript’s C-like syntax… makes it appear to be an ordinary procedural language. This is misleading because JavaScript has more in common with functional languages like Lisp or Scheme than with C or Java.”

    Apparently the language was named JavaScript as a marketing thing as Java was “it” at the time. Awfully confusing choice of name!

  93. Jimbo Baggins
    Permalink to comment#

    Speaking of javascript, I get a js error when viewing this website in ie7. I think you’re missing or have an extra comma somewhere in your js.

  94. My biggest Javascript “Ah-ha moment” was when I found out that you have to define functions in AJAX callbacks so the newly loaded content can access your functions.

  95. My “Ah ha!” moment was the day that a friend told me about a new framework that was on development called jQuery.

  96. I have yet to experience my ‘aha’ moment for javascript in particular, but along a similar line is my ‘aha’ moment for Object-Oriented design in general. I was banging my head against the wall all evening trying to get some code working, and went to bed. I woke up in the middle of the night and thought to myself… “Wait! I get it!”. I realized that I had been stumbling through my code with some hodgepodge of procedural-OOP-spaghetti mess. I suddenly understood the whole concept of creating an object once and using anywhere throughout the site, or any of my sites for that matter. I knew what it meant to write a self-contained class that could be used wherever I needed it, across all of my projects. It was like a paradigm shift for me. It was a cool feeling.

  97. Had my “Ah ha!” when I realized that I can do jQuery, but no raw JavaScript. And I’m still not sure if this is a good or bad thing – but it works for me.

    • I’m just the opposite. I know my way around jQuery, but unless a client demands it, I’d take vanilla Javascript over a library any day.

      Yes, I know the risks (browser inconsistencies mainly), but I have yet to see a decent library that actually encourages to use Javascript the way it’s meant to be used. My problem with them is more about the mentality behind them than the frameworks themselves.

      Javascript should not be used for animation or styling; one should use CSS. It shouldn’t be used for content generation or script loading; one should use a server-sided language or just HTML for that. Most important, a website should not rely on Javascript to function (except in special cases, such as Gmail or something similar).

      Worst of all, though the frameworks themselves are rarely that big, relying on them can quickly bloat a website. My company’s ‘mobile site’ had to load over a megabyte of JS libraries just to function, and it’s perceived loading time was 3 times longer than that of the desktop website.

      I guess what I’m saying is that it’s good to know the fundamentals, if possible.

  98. Permalink to comment#

    I wrote a very small and basic jQuery Truncate Function (http://martoosterveld.nl/blogdetail.php?id=27). That was my Ah ha Moment; from that I started to get better and better in JS and jQuery. Still have a lot to learn but this definitely was the beginning of a good JS carreer for me :)

  99. Permalink to comment#

    First when I realised there are two ways to access object properties:

    var x = {};
    x.foo = "rainbows";
    x["foo"] = "unicorns";

    Then when I realised the second type doesn’t even have to use a string:

    var x = {},
        y; // undefined
    
    x[y] = "clouds";
    x[undefined]; // "clouds"

    or maybe:

    var x, y;
    x = {
        foo: "rainbows",
        bar: "unicorns"
    };
    
    y = function (a) {
        return a * a;
    };
    
    x[y] = {
        madness: "SPARTA"
    };

    or even:

    var x = {};
    x[x] = "turtles";
    • Careful there, the object you use within the brackets will be indexed using its string representation (toString() will be called), so if that turns out to be “object Object”, and you’re not aware of that, then you can end up with some unexpected collisions.

    • Permalink to comment#

      Hmm, now that’s interesting, I didn’t know that, thanks :)

  100. For me it was the moment I discovered I can debug JavaScript in the Firebug console using debugger;

  101. Web Master Design
    Permalink to comment#

    Good Post! Here’s some tips on how one can evolve themselves in the field of web design:
    1. Keep up to date with news through design blogs or perhaps learn a new web language.
    2. There are many fantastic web design books and magazines out there covering a wide range of subjects with ever-increasing depth as a source of education.
    3. Web resources like Six Revisions are great for learning new techniques.
    4. Remember to verify anything you learn through a third party resource. There’s an awful lot of outdated information out there (like W3Schools) that could get rid of those bad habits.
    5. Sites are beginning to teach classroom-style lessons and video-based instruction classes (e.g. Lynda.com) on web design and development. They can get pricey, but they will be best investments for your future.

  102. simon
    Permalink to comment#

    a-ha! numbers, boolean, strings etc..
    a-ha! if else
    a-ha! for / while loops
    a-ha! functions, objects, methods

    until i will know the whole grammar of this language, there will be a few more a-ha moments. for me, the most important a-ha moments will be, when i realise what i can do with the DOM. for me, as i am not writing real computer programs, it will be most important what i can do to my webdesign with js. to do this things the best, cleanest and lightest way, i think its important to everyone to know how pure js works.

    a really good source to learn javascript is codeacademy which i am actually using. for me, there has never been an easier way to learn a web-related technology, so i can really recommend it to everyone.

  103. This thread is turning out to be an excellent tool for compiling a reading list as a jQuery/future plain JavaScript developer. The recurring themes cited by advanced JavaScript developers that took them to the next level are really inspiring me to learn, and giving me some great direction with which to do so.

  104. Ampersand
    Permalink to comment#

    The moment when I realized the difference between this and $(this).

  105. I wouldn’t claim I have a “decent understanding” of Javascript, or anything for that matter, but watching a series of talks by Douglas Crockford blew my mind. While my code is still a silly mess, at least know I know what sucks about it (to some degree at least), and more importantly I now can think stuff up and get it working in some shape or form without much pain — instead of at best modifying copypasta while having hardly any clue how and why it works, and at worst just having to pass.

    http://yuiblog.com/crockford/

    ^ they’re on youtube, too. If you’re like me, you might have a fever like reaction to it: unable to stop watching, while feeling the urge to put what you’re hearing to practice, which is a bit like needing to sneeze and pee at the same time. Best brain pain ever! Personally, I’m looking forward to watching them all again at some point in the future and actually being somewhat able to follow, that will be awesome as well.

    Hope this helped anyone, and thanks to Crockford either way.

  106. My ahha moment was picking up JQuery. I guess you could say I’m still waiting…

  107. When i use alert type validation and my sir told me to use better and stylish validation and it works in first time

    well its not like that ah ha so i’m still waiting

  108. Ivaylo
    Permalink to comment#

    Biggest Aha so far – we are stuck with it… (so better learn it)

  109. Patrick miravalle
    Permalink to comment#

    My ah-ha! moment was definitely when I grasped the concept of “this”, both in javascript and in php! It’s such a simple concept yet it can be so difficult to wrap your head around at first. Once I got that down, my programming life became a hell of a lot easier.

  110. I’m a professional or anything like that but I would say that moment came along when I figured out how to display data from other pages using JavaScript/jQuery after weeks of searching.

  111. My aha moment was when I learned the power and ease of truthy and falsey expressions in JS. No more “if (x == “” || x ==0 || typeof x == “undefined”)”, now I can just do “if (x)” #booyah

  112. jQuery aha!
    - Chaining and callback functions.

    Javascript aha!
    - How objects work and how to use them.
    - What is and how exactly the DOM works

  113. Permalink to comment#

    I am still waiting for a AH AH moment. I read tutorials, watched videos but I still can’t wrap my head around Jquery. I mean I can do the simple stuff like hide and slide this down but besides that I can’t go any further. I don’t know what it is…I don’t even know what an Object is! UGH. Sadness.

    • Leo
      Permalink to comment#

      Im in the same trouble here mate, I can seem to manage little things like slide, hide etc, but nothing else and I’m desperate about getting this ah haaa moment, I’m watching video tutorials, reading books, tryed code academy, but nothing seems to click for me ((( I asked about suggestion here but no one answered, please if anyone any shortcut or hint, tip, tutorial please post…

    • Rodrigo
      Permalink to comment#

      Leo,
      Have you tried meeting up with others and trying to learn in a group setting?

      For me what’s helped me was deciding to take a course at a school to learn the basic fundamentals, which has really helped me get a better understanding of what’s going.

      Prior to this I had tried everything you described and nothing caught on. I think it comes down to knowing yourself and how you learn best.

      I still have a long way to go with lots of sleepless nights, but I’m setting a good foundation.

  114. Darren
    Permalink to comment#

    Amazing similarity to all these moments when the ‘penny dropped’. It was exactly the same for me, I got to learn that everything was an object fairly early on…

    And then you think you’ve got it nailed, you start throwing stuff out there and bam! namespace conflicts with plugins or other bits of code – and you’re back to being humble once more… you learn about namespacing and closures and stuff…

    And then ‘this’ – you think what the hell is ‘this’, oh woe of man did it take me forever to ‘get’ this, or is it ‘get this’ or maybe get ‘this’, one thing for sure is when you do get this, you’ve got it.

  115. I’m still “getting” JS, but for me, the biggest “ah-ha” moments I’ve had were when I figured out how if/else statements work(just like PHP!), how to use console.log(), and that JS is essentially just variables and functions–in that order.

    I’m working toward my next ah-ha moment by diving into encapsulation :)

  116. For me its when I found the phpjs.org

    All the PHP functions converted to JavaScript….

  117. caspian
    Permalink to comment#

    I think Chris’s explanation of jQuery just gave me my jQuery aha moment.

  118. My ah-ha moment was the prototype in Javascript. I already knew the ‘everything is an object’ from my explorations of Ruby, so that made sense – it was the lack of classes that really broke Javascript in my head. Then I read Javascript: The Good Parts and he nails the prototypal nature of Javascript.

    That’s when something clicked in my head (I was reading about evolutionary theory at the time as well) and I put prototype with ‘last common ancestor’ and it really just clicked: Extend a class by finding the prototype object down the chain that should carry the extension, and diverge from there.

    Really, all of Javascript: TGP is one big ‘oh THAT’S how you do that’ moment.

  119. Permalink to comment#

    Objects scopes, “knowing what is *this* referring to at any time”, and the DOM event system, “learning that you can #addEventListener”.

    Anyway, I use CoffeeScript now, it really simplifies everything.

    In CoffeeScript something like this…

    
    function someFun(){
    ▉setTimeout(function(){
    ▉▉alert(this);
    ▉}, 100);
    }
    

    Becomes this…

    
    someFun = ->
    ▉setTimeout ->
    ▉▉alert(this)
    ▉, 100
    

    And the most amazing thing, something like this…

    
    function someFun(){
    ▉_this = this;
    ▉setTimeout(function(){
    ▉▉alert(_this);
    ▉}, 100);
    }
    

    Can be written like this…

    
    someFun = ->
    ▉setTimeout =>
    ▉▉alert(this)
    ▉, 100
    
  120. Mark
    Permalink to comment#

    Prototypical inheritance is probably one of the hardest concepts I had to wrap my head around, but once I realized how this paradigm worked. I always wanted Javascript to be clean and class-based, but the prototype chain was a new outlook on programming.

  121. Krev
    Permalink to comment#

    Discovering jQuery to get away from that mess.

  122. I started learning JavaScript long time ago, it will be over 10 years now, way before I had my first Internet connection. The content from I was learning was a simple JavaScript web tutorial, zipped on a diskette, and a tutorial in a computer magazine. Because of that I was mostly discovering the language by myself, so there was many Aha! moments.
    My code then was a total mess (Whitespaces and new lines? Who needs that! The more code will fit your screen the better), but weirdly I completely knew what was going on there.
    I wasn’t using var statements, because I didn’t see the difference between it and simply just using a variable. Later on I discovered, that the attributes in functions have strange ability not to be seen beyond function. So I starting using it like this:

    function funcName(xCoord, yCoord, i, coordsMean, regExp) {
        /* code */
    }
    funcName(13, 50);

    which with my current style of writing looked like this:

    /*some code here*/function fn(x,y,i,temp1,temp2){/*code*/};fn(13,50);/*code here*/

    Then I tried var again.
    It was probably my biggest Aha! moment.

    My latest Aha! moment is about this:

    (object.method || function () {})(param); // doesn't work as expected
    (object.method || function () {}).call(object, param); // Aha! I must use call here
    object.method && object.method(param); // after all I choose this anyway

    Yeah, comment a little bit TL;DRy, but I hope you liked it :)

    • How does (object.method || function(){})(param); not work as expected? Perhaps your expectation was wrong, but that does do what you’re telling it to. (although it seems to favour anonymous functions, which are a poor substitute for functions which can be referenced by name).

    • Well, as you can see from the second line, my expectation of this invocation’s effects was different. Maybe I didn’t express that clearly enough, I should have written “… as expected by me”.
      What do you mean by “poor substitute”? Performance issues? Well, performance wasn’t so important there so I wrote in a way that is easy understandable by me. I often use construction like (object.notSureIfThisPropertyWillExist || {}).foo, so I wanted to use something similar for methods. Maybe I should start using some global scoped noop function, but for now I don’t feel need for that. Anyhow I have chosen the third option (which is really the second one).

      But feel free to criticize my code/style/habits. I’d love to learn something more and therefore be a better programmer.

      Cheers.

    • Well, no. I meant the statement (x || y)() is saying “call x, if it isn’t there then call y”. In your example x is a function on an object that you can call multiple times (that’s the point of public functions right?), but y is not. This problem is usually approached this way: if(!x) x = y; which says “if x isn’t there, then y is x” – That’s how most shims work.

    • But that is not a shim. I don’t want to replace that nonexistent method with a noop.
      The role of this expression was rather something similar to a try statement (or @ in PHP). A try statement, which is considered rather slow and is advised to be used in the topmost scope (and I used it there), was just not so necessary here, because I can do checking with if or || or &&.
      You said:

      “In your example x is a function on an object that you can call multiple times (that’s the point of public functions right?), but y is not.”

      and that was exactly my goal. The noop there was meant not to be called at any time. It was there just for precaution, so when it does happen to be called, the program will move ahead, not throwing “TypeError: undefined is not a function” (especially when code is executed server-side, like here).
      I hope that clarifies some things. Thank you for your comment, I appreciate it. I can assure you that when some code is executed many times I try to find for it some cosy place in memory :)

      Cheers.

      P.S. I misclicked and that comment landed up to the main thread. Please ignore it. Sorry ^_^’

    • Oh, I now get where the confusion may come from. I showed a generalized example:

      (object.method || function () {})(param);

      I just wanted to call attention to calling a method. In reality that was looking a bit different:

      (object[methodName] || function () {})();

      Now watching that from a different perspective it may look like I was trying to achieve something else.

      Nevertheless, that still might look confusing why I was even trying such an approach. But trust me, in context that suits much better than you think.

      Cheers.

  123. Excellent post. It’s incredible how many people go through the same experiences.
    I too had “Aha” moments. My first one was when I dicovered that jQuery is not some alien language and that it’s so easy to understand.

  124. But that is not a shim. I don’t want to replace that nonexistent method with a noop.
    The role of this expression was rather something similar to a try statement (or @ in PHP). A try statement, which is considered rather slow and is advised to be used in the topmost scope (and I used it there), was just not so necessary here, because I can do checking with if or || or &&.
    You said:

    In your example x is a function on an object that you can call multiple times (that’s the point of public functions right?), but y is not.

    and that was exactly my goal. The noop there was meant not to be called at any time. It was there just for precaution, so when it does happen to be called, the program will move ahead, not throwing “TypeError: undefined is not a function” (especially when code is executed server-side, like here).
    I hope that clarifies some things. Thank you for your comment, I appreciate it. I can assure you that when some code is executed many times I try to find for it some cosy place in memory :)

    Cheers.

    • That upper comment was meant to be a reply, I posted it above, so you can ignore or delete it (if you are able to). Sorry for inconvenience, my bad ^_^’

    • :) That’s the first time you mentioned no-op!!! I didn’t take your empty function literally, I thought that was for brevity. Yeah, I don’t see anything wrong with if(x) x(); personally. I mean, compared to x && x(), that’s not a very nice thing to do for other developers who don’t have JavaScript as their first language.

  125. Mine would have to be learning how easy it is to do asynchronous xml/http request:
    —–
    var req = (window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject(“Microsoft.XMLHTTP”);

    if(req == null) throw “Error!”;

    req.onload = function() {console.log(“Success!”);}

    try {
    req.open(“POST”, address, true);
    req.send(data);
    } catch(e) {throw “Error!”;}

    —–

    For the longest time, I thought AJAX was some amazing Javascript ‘thing’ that required advanced frameworks to implement.

    I also had another (somewhat perturbing) “aha” moment shortly after when I discovered that most libraries that use “AJAX” encourage to use it to inject raw HTML/Javascript into webpages (parse errors and security holes galore!).

  126. Mine was when I read that, while OOP adds behaviors (methods) on states, Javascript functional approach was just the inverse : allowing state into functions.

  127. Dean
    Permalink to comment#

    The moment when I tried to create my own accordion script because I found the one in jQuery kind of hard to set up.

    And I didn’t even know how to code any Javascript, so that meant reading through the docs and learning the language.

Leave a Comment

Current day month ye@r *

*May or may not contain any actual "CSS" or "Tricks".