Page 1 of 2 12 LastLast
Results 1 to 10 of 11

Thread: Book Blog: Secrets Of The JavaScript Ninja

  1. #1
    Senior Member Tetris Champion notdavidlynch's Avatar
    Type
    INXP
    Join Date
    Dec 2013
    Posts
    2,043

    Book Blog: Secrets Of The JavaScript Ninja

    So, in my quest to rid myself of cowboy coding tendencies, I've decided that I might try to.. learn a little more. I figure that keeping a book blog will be helpful to document my cursory thoughts and impressions and to be able to refer back to them later.

    Secrets Of The JavaScript Ninja is written primarily by John Resig. You may recognize the name. He's the guy who created jQuery. Maybe you've heard of it. He also works at Khan Academy (ugh), and created Processing.js - which I personally view as a catastrophic failure, though that may simply be because he pretty much abandoned it. When I originally attempted to use Processing.js for a project, I was mostly familiar with Java and didn't have much understanding of the limitations and differences of JS running on a browser - thus ditching it half-way through, though now that I think about it, I probably could've finished if I weren't so quick to jump back to what was familiar. All that aside, he also studies Ukiyo-e and is probably a weebo.

    So, why JavaScript? If you've been paying attention, you likely know that JavaScript is important, now moreso than ever. Web applications are more robust and interactive, and JS is no longer even limited to browsers. Rhino, V8 and Node.js have JS being used as a backend language, and recently it has even started to be used for native mobile app development.

    Basically, it's fucking everywhere, and the author seems to think that pretty much everyone fucking sucks at writing it. He talks about how to best learn to not suck at it in Chapter 1, and concludes the intro with various notes, roadmaps, who the book is for, etc.

    Who is the book for? Not for rank novices, but pretty much everyone else can benefit.

  2. #2
    Sysop Ptah's Avatar
    Type
    INTP
    Join Date
    Dec 2013
    Location
    Chicago
    Posts
    4,032
    JavaScript/ECMAScript =
    jQuery =

  3. #3
    Mens bona regnum possidet ferrus's Avatar
    Type
    INTP
    Join Date
    Dec 2013
    Location
    Barcelona, Catalonia
    Posts
    5,669
    Quote Originally Posted by Ptah View Post
    JavaScript/ECMAScript =
    jQuery =
    I think we need a Hustler style deathmatch thread between smartphones and jQuery to annoy you.
    Die Logik ist keine Lehre, sondern ein Spiegelbild der Welt. Die Logik ist transcendental. - Wittgenstein

  4. #4
    Sysop Ptah's Avatar
    Type
    INTP
    Join Date
    Dec 2013
    Location
    Chicago
    Posts
    4,032
    So, why JavaScript? If you've been paying attention, you likely know that JavaScript is important, now moreso than ever. Web applications are more robust and interactive, and JS is no longer even limited to browsers. Rhino, V8 and Node.js have JS being used as a backend language, and recently it has even started to be used for native mobile app development.
    Yup. I agree with that. Although in some cases, it has been distended, as such.

    Basically, it's fucking everywhere, and the author seems to think that pretty much everyone fucking sucks at writing it. He talks about how to best learn to not suck at it in Chapter 1, and concludes the intro with various notes, roadmaps, who the book is for, etc.
    I agree, most everyone does suck at JavaScript. And the likes of jQuery just makes it worse. So fuck jQuery and fuck the guy who made it. Most of all, fuck anyone and everyone who whatsoever abides its existence.

    Too large a portion of my job is re-writing halfwit jQuery-based bullshit slung by other coders. I strip it out and replace it with non-jQuery (as in: js + om up) stuff that works just as well if not better, and has none of the bullshit side-effects or costs of jQuery. jQuery is a fucking disease. A rash. A blight upon the language and its use.

  5. #5
    Married Mouth-breather JohnClay's Avatar
    Type
    INTP
    Join Date
    Dec 2013
    Posts
    2,001
    INTPx Award Winner
    Quote Originally Posted by Ptah View Post
    JavaScript/ECMAScript =
    jQuery =
    I use jQuery a lot and so do the programmers I work with. I might learn how to make a plugin one day. I like how I can do things like AJAX with it. I think it is good for cross-browser compatibility, especially for pre-version 2.

  6. #6
    Senior Member Tetris Champion notdavidlynch's Avatar
    Type
    INXP
    Join Date
    Dec 2013
    Posts
    2,043
    In Chapter 1 Resig goes into explaining how he thinks people can become better JS programmers. The gist of it seems to be that the best way to learn is by analyzing cross-browser compatibility in the top JS libraries (at the time): jQuery, Prototype, Yahoo! UI and base2.

    He then threw around some terms I didn't really understand at the time and rambled for a bit before getting back to his original point that to be an expert web application developer, you need to 1) understand the language, 2) understand cross-browser coding issues, 3) employ good testing, 4) employ performance analysis and 5) know how to debug. The last 3 are "best practices" that no one ever taught me and that I've never bothered to learn on my own. Testing is done with lots of asserts - assert(condition, message), etc. Performance analysis is typically done with timestamp differences. Modern browsers usually have built in debuggers.

    Some of the things mentioned that I had to look up:

    "anonymous inline functions" (defined inline without a name?) and "closures" - brought up discussing (IIRC) why JS is more of a functional rather than object oriented language. Internet tells me that JS is closer to lisp or scheme dressed up in C style syntax. Which I'm starting to believe simply because some of the later examples were coded in ways that just felt weird to me coming from C and Java. Was already familiar with higher order functions and callbacks.

    He basically thinks that functions are more important than anything else in JS. Object/function/closure triadic relationship.

    He says that timers and regular expressions are woefully underused, and that the with statement and eval() method are condemned and misused.

    Describes "graded browser support", basically a cost/benefit analysis focusing on the target audience, market share and effort involved in supporting a particular browser/version. Looking at gs.statcounter.com - it appears that things have changed a lot since the book was written. Chrome is far and away the most dominant browser.

    Reiterates that cross-browser web app development is hard.

    Might be writing/remembering all of this out-of-order.
    Last edited by notdavidlynch; 01-30-2015 at 11:22 AM.

  7. #7
    Senior Member Tetris Champion notdavidlynch's Avatar
    Type
    INXP
    Join Date
    Dec 2013
    Posts
    2,043
    Chapter 2 basically sets the groundwork for testing assertions (which the author repeatedly does for just about every concept/example in the book). A very simple framework for testing is given, here it is:

    Code:
    <html><head>
      <title>Test Suite</title>
      <script>
      function assert(value, desc) {
        var li = document.createElement("li");
        li.className = value ? "pass" : "fail";
        li.appendChild(document.createTextNode(desc));
        document.getElementById("results").appendChild(li);
      }
      </script>
      <style>
      #results li.pass { color: green; }
      #results li.fail { color: red; }
      </style>
    </head>
    <body>
     <ul id="results"></ul>
    </body>
    <script type="text/javascript">
    
    
      /* Insert crap to test with assert() here, the author didn't put this 2nd script tag at the bottom. I did, just because. */
    
    
    </script>
    </html>
    Another test suite is built for asynchronous testing. Assertions are bundled into test groups and each group is placed on a queue to be run after previous placed groups have finished. I was a bit confused because the example of this was written with a self-invoking function, which I hadn't seen or used before, but it's a pretty simple idea. I'm not going to post the code for the asynchronous test suite. I haven't used it yet.

    You also probably don't even need to have your own custom test suite written. There are so many already. At the time of the writing the major ones were JS Bin, QUnit, Selenium and YUI test. Others include FireUnit, Prototype, Screw.Unit, Envjs, JSSPec and Dojo. Author says to also be aware of Jasmine and TestSwarm. I haven't really looked at any of these yet.

    Early on he also discussed developer tools like Firebug which I won't talk much about. I'm already fairly familiar with Firebug and Chrome developer tools and I assume that anyone serious about development is as well - same goes for console logging, breakpoints, etc.

    General ideas: Tests should ideally be reproducible, simple and independent. There are deconstructive and constructive test cases, the utility of each I'm not clear on at the moment.

  8. #8
    Senior Member Tetris Champion notdavidlynch's Avatar
    Type
    INXP
    Join Date
    Dec 2013
    Posts
    2,043

    Post

    Chapter 3

    Now we begin. He once again makes it clear that he thinks that JavaScript is a functional language, so the ins and outs of how functions work in JS should be studied first. He says that people who bitch and complain about JavaScript tend to be people who were exposed to a language like C or Java first, and that they probably try to use JavaScript like the language that they're more familiar with when they're not all that alike other than C-style syntax.

    The joke is that JavaScript has as much to do with Java as a hamburger has to do with ham.

    The function is the primary unit of execution in JS. Functions are "first-class objects", meaning they can be treated like any other object: referenced by variables, declared with literals, passed as function parameters, stored as array entries, become properties of other objects, returned as values from functions, possess dynamic properties, etc. But, unlike other objects, functions can be invoked.

    He then goes on to discuss the basics of the browser loop (which is single-threaded) and how it handles the dispatching of events such as mouse clicks. Events are put in a FIFO queue as they occur and are dispatched by invoking handlers (functions) created by us, which are typically asynchronous (unpredictable timing, order).

    Different types of events: browser events (page loading, etc), network events (responses to ajax requests, etc), user events (aforementioned mouse clicks, key presses, etc) and timer events (expirations, intervals).

    window.onload = function() { blah blah blah };
    ^ browser event, ^ established handler

    Introduces the idea of "unobtrusive javascript", which is keeping JS as separated as possible from the HTML and CSS (i.e. keeping as much of it as possible in a separate file).

    I thought it important to note that in JS there's the ability "to create functions anywhere in the code where an expression can appear".

    This was a pretty long chapter. He goes on to break down how declaration and invocation works. I'll try to keep it brief and leave out the more obvious stuff.

    Declaration


    • For top-level declared functions, a property reference is attached to the browsers window object
    • All functions have a property named name that stores the functions name as a string, even if it's an empty string
    • Functions work within and create scopes
    • Code blocks apart from function declarations - which are typically created with () or {} - have no bearing on function or variable scope, this probably needs an example:


    Code:
                
    if (window) {
        var x = 123;
    } // this block of code doesn't create a scope
    alert(x); // this actually alerts 123

    • named functions are in scope within the entire function in which they're declared (this only goes up one level)
    • the global context acts as one big function


    Invocation


    • functions can be invoked as a function (duh)
    • or as a method, constructor, or by the apply() or call() methods
    • excess arguments are not supplied to parameter names but can still be accessed
    • unsupplied parameters are set to undefined
    • all function invocations have 2 implicit parameters: arguments (where you can access an indexed, iterable collection of all arguments supplied - not technically an array) and this (which refers to a "function context" object)
    • when invoking as a function the context is global, referencing the window object
    • when invoking as a method, like o.whatever(); the context is the o object


    Invoking as a constructor is a special case. This is what happens:
    1. New empty object created
    2. Object is passed to constructor as this parameter, becomes function context
    3. Unless there is an explicit return value, the new object is returned


    Functions intended to be used as constructors can be used as normal functions, but that would be dumb. Because of this, the naming convention for constructor functions vs. normal functions is different: normal functions are typically verbs/descriptive of an action that start with a lower case letter and are camel case afterwards - ex. thisDoesSomething(); while constructor functions are named as nouns and start with a capital letter - ex. Something();

    Invoking with apply() and call() is a little weird so I'm not sure I want to detail it. It basically allows you to specify arbitrary objects to use as a context for function invocation. It's not clear yet why this is important or useful yet, but the author discussed them in relation to the "for-each" loop style that is preferred in JS over the traditional for loop.

    Hmm.

  9. #9
    igKnight Hephaestus's Avatar
    Type
    INTP
    Join Date
    Dec 2013
    Location
    Ceti Alpha V
    Posts
    9,142
    Quote Originally Posted by notdavidlynch View Post
    The last 3 are "best practices" that no one ever taught me and that I've never bothered to learn on my own. Testing is done with lots of asserts - assert(condition, message), etc. Performance analysis is typically done with timestamp differences. Modern browsers usually have built in debuggers.
    The second one (to my mind) falls under the umbrella of the others. Those first one, and last three are what I would consider the foundations of being a good programmer. You gotta know how to test and debug, period. They're critical, but undervalued because they don't directly make money because they don't produce new functionality. Performance analysis is further down the list, but without it, you'll never make great code, and more importantly, you'll never know why your code sucks or how it could be improved. Protip: doing it in one line doesn't mean it's more efficient. I was very sad to realize that.

    The other stuff smells about right too. Regular expressions are underused, but there's a good reason for it. They're scary powerful and incredibly easy to get wrong, and difficult to unfuck.

    Timers are tricky, but useful. There's a reason the 555 timer chip is still a fucking king after all. I say timers are tricky because every time you throw one in, you're adding overhead to your code, so using a lot of them seems like bringing your own quagmire. I'll admit, I don't know how to leverage them to best use other than for entertainment purposes, or to force a halt to something that's taking longer than I want it to.

    But, I do remember playing a game called Carnage Heart. It was an impossible concept game, by which I mean, it's amazing it ever got made and I have my doubts it could happen again--though I'm probably wrong about that. People make ALU's in Minecraft after all.

    Carnage Heart put you in the role of a hardware programmer type. It was GUI based programming on a grid to automate a bot to fight other bots. It was a game about making a better AI to beat up the AI's dreamed up by the programmers. Sexy concept to a small portion of the population to be sure. I played with it for quite some time, and thing I remember most was that the timers and counters were the most critical and common components used for a successful AI.

    Inline functions, and anonymous inline functions I'm kind of with you on the whole headscratching thing. But mostly because they are sooooo slow compared to regular functions. However, they (and anonymous inlines in particular) start to look more interesting when you start thinking about self-modifying code. An anonymous inline function still has a pointer, and you can hook that pointer up to an alias, or an array of pointers or fire and forget (assuming GC kicks in appropriately). But really, it's the ability to have code that can make and name it's own functions on the fly that I think make anonymous in-line functions worth doing.

    Once you start thinking about it, it makes a lot of sense. I mean, it's the most obvious means to make a REPL loop isn't it? Take in a string, parse it, return a pointer to the newly compiled code.
    --Mention of these things is so taboo, they aren't even allowed a name for the prohibition. It is just not done.

  10. #10
    Senior Member Tetris Champion notdavidlynch's Avatar
    Type
    INXP
    Join Date
    Dec 2013
    Posts
    2,043

    Post

    Chapter 4

    This chapter took a bit to slog through. Some of the material was kinda hard to read because it relied on uncovered concepts. With some more I just couldn't imagine remembering the particular techniques or spotting opportunities to apply them. Anyways..

    It starts with a discussion of anonymous functions. They're just unnamed functions. In JS, functions tend to be created and disposed of quickly, as needed, living ephemeral lives. Either that, or they're just attached to property names. I guess that's important (?): the name of the property attached to a function is not the name of the function. Anon functions are also frequently passed as callbacks.

    A purported benefit of anon functions is that they don't "pollute" the global namespace, and facilitate creating lots of little functions to pass around instead of large ones full of imperative statements.

    A somewhat interesting discussion of recursion follows. Simple example of a recursive function to decide if something is a palindrome:

    Code:
    function isPalindrome(text) {
      if (text.length <= 1) return true;
      if (text.charAt(0) != text.charAt(text.length - 1)) return false;
      return isPalindrome(text.substr(1,text.length - 2));
    }
    * 2 criteria for recursion: reference to self, convergence towards termination

    Discusses differences between recursion with named and anonymous functions used as methods of an object. Basically, it's wise to call an anonymous recursive function with this instead of the name of the object that it's defined within. This is so that other objects can appropriate the recursive function and still use it if the original object disappears (?).

    BUT, you can also just give these inline functions names. All functions can have names, even those used for methods or callbacks. An important point about this, however, is that even though inline functions can be named, the names are only visible within the functions that declare them. So this can be used for recursion but not much else, and this is also why top-level functions are created as methods on the window object.

    The callee property is discussed, but it's on the chopping block (?). Not going to discuss it here.
    Since functions are first-class objects, you can attach properties to them . But why? You can attach an id to a function to determine if it's unique. You can also write functions that remember previously computed values, called memoization. This likely sacrifices memory in favor of performance, and it's difficult to test the performance.

    Will start being brief (likely from here to the end of the book). The author describes what he thinks of as a "nefarious" technique for simulating array behavior. Basically creating normal objects, filling them with data and then using call() to add Array.prototype methods to this new object.

    Long discussion of the benefits of functions that can accept an arbitrary number of objects. There's a sort of interesting example of applying Math.max and Math.min to array objects (using apply()). Another example of traversing variable length argument lists to merge objects, and using Array methods to slice an argument list.

    It lost me when it went into a method-overloading function because it involves closures.

    There are also cross browser issues with determining if something is a function. It said that Firefox treates the <object> element as a function. I tested this to see if it's still true, and it is. Most of the time, however, simply using typeof should work.

    Small things I noticed:

    • With fn.id = store.nextId++; it first sets the value of fn.id to store.nextId, then increments store.nextId.
    • !!(blah blah blah); converts blah blah blah into it's boolean equivalent.


    Really glazed over most of the details in this chapter.
    Last edited by notdavidlynch; 02-05-2015 at 10:19 AM.

Similar Threads

  1. PH's Book Club: Icelandic Literature - Independent People and Njáls Saga
    By Penguinhunter in forum Arts & Entertainment
    Replies: 5
    Last Post: 06-03-2016, 05:52 AM
  2. Book Club: Season of Migration to the North
    By Penguinhunter in forum Arts & Entertainment
    Replies: 1
    Last Post: 03-30-2014, 12:49 AM
  3. PH's Book Club - The Risky Democratic Path
    By Penguinhunter in forum Arts & Entertainment
    Replies: 10
    Last Post: 03-11-2014, 03:41 AM
  4. Replies: 2
    Last Post: 02-09-2014, 01:07 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •