All I Want for Christmas: Effective JavaScript — Book Giveaway

Originally published at: http://www.sitepoint.com/want-christmas-effective-javascript/

We asked SitePoint authors what developer toys they would want for Christmas, then managed to source them — without relying on Santa.

“Effective JavaScript” is a new book by experienced developer David Herman, taking an in-depth look at JavaScript, with information and advice on how to write more portable, robust and maintainable apps and libraries.

Why I wanted this book

In the course of my day job, I write a fair amount of JavaScript and am reasonably proficient at the “normal stuff”, such as making AJAX requests or manipulating the DOM. However, of late I have felt a growing need to get to grips with the inner workings of the language, and attempt to grok some of its more complicated concepts. That’s why “Effective JavaScript” by David Herman was right up there on my Christmas wish list.

The experience so far

The book surpassed my expectations. David (a senior researcher at Mozilla and serving member of the TC39 committee) takes us on an in-depth tour of the language, covering everything from prototype-based object-oriented programming to JS programming patterns and idioms. Along the way, he illuminates many of the language’s pitfalls whilst providing a wealth of realistic use cases. Doubly pleasing was the fact that the book is structured around 68 “items”, meaning that it can be dipped into at will, read in any order and/or used as a reference book.

As a self-taught coder this book has helped me fill several gaps in my knowledge. It is well-written, concise (200 pages) and I can heartily recommend it to anyone wanting to take their JS skills to the next level.

All I Want for Christmas:

Continue reading this article on SitePoint

I think the classic IIFE (Imediately Invoked Function Expression) is likely one of the slickest concepts.

(function(){
  //add your magic here
})();

With the ability to run your private code within it, be able to pass in whatever you want access to into it, and not pollute the global scope?.. Priceless!

2 Likes

I recently started learning JavaScript in-depth and this book will go a long way to helping me understand JavaScript.

Gah! Douglas Crockford has infected my brain on how invoking the function is preferable to invoking the parenthesis.

(function () {
  //add your magic here
}()); // good - the function is being invoked
(function () {
  //add your magic here
})(); // bad, this is trying to invoke the surrounding parenthesis

Also with the good example, the surrounding parenthesis make it clear that the function is not your standard one, and is inside the parenthesis in order to turn it in to a function expression.

It’s made nice and clear in his Programming Style & Your Brain @27:28 video, and I highly recommend rewinding from that spot to enjoy the rest of his talk too.

1 Like

Thanks Paul. What little I know of JS, I really do like IIFEs, and just took DC’s advice on which version to use without understanding the difference. Thanks for your explanation, and for the link. I look forward to watching it.

He has another reason for placing the invoking parenthesis inside with the function, which is that it’s more consistent with how we call functions in the first place.

If we have a function, we don’t call it inside of parenthesis:

function someFunc() {
    // ...
}
(someFunc)(); // a bad example of calling a function

Instead, the invoking parenthesis go directly with the function - this is the normal way of using functions, even when parenthesis are involved.

function someFunc() {
    // ...
}
(someFunc()); // a good example of calling a function

The normal thing to expect is that the function and the invoking parenthesis are directly beside each other, which helps to explain Crockford’s preference - it’s the principle of least astonishment.

(function () {
    // ...
})(); // bad - violates the principle of least astonishment
(function () {
    // ...
}()); // good - invoking parenthesis right beside the function

The second example is not as good because the parenthesis is being invoked. I’ve seen cases where the last line is not actually invoking the function, but is doing other unexpected stuff instead.

And, Crockford equates the last example with the () hanging out off the end as being visually similar to dogs balls, which helps to put the nail in the coffin.

Oh, no - I’ve seen things . . . I’ll take my leave :slight_smile:

1 Like

So he prefers his IIFEs neutered, eh? :stuck_out_tongue:

I really like querySelector() and querySelectorAll(). There are so many nice little additions to JS these days that make it more appealing to hold off using a library for selecting elements, adding/removing classes etc.

My favorite javascript tidbit is:

alert (“I’m working.”)

Being a newbie, this is the best and easiest way to test whether the damn thing is running or not. :confused:

So clearly I need this book more than the lot of you :smiley:

1 Like

My favourite one of the past year or so has been classList protocol to let you easily manipulate the class names of an element.

1 Like

Yes, I had to toss up between that and querySelector, but decided I use one a lot more than t’other.

On this topic I disagree with DC

  function(){}()    // Syntax error.
( function(){}() )  // Astonishment! Why did the syntax error go away?
( function(){} )()  // Of course, the parentheses make it clear what goes together.

I don’t even want the book. I just came to make a point.

2 Likes

Partial application using .bind() is probably my favourite.

Example:

function add(a, b, c, d) { return a + b + c + d; }

// returns a function that has an airity of one (d) and has a, b and c partially applied
var partiallyAppliedAdd = add.bind(null, 1, 2, 3);

var x = add(1,2,3,4); // 10
var y = partiallyAppliedAdd(4); // 10
assert(x, y); // true

also these are pretty nice.

// a double bitwise not operator acts like Math.floor
var x = Math.floor(10.9); // 10
var y = ~~10.9; // 10
assert(x, y); // true

// prefixing new Date() with a '+' will give you a unix timestamp
var z = +new Date(); // 1418763280491 at the time of writing this

// in es6 - pattern matching
var person = {fname: "Bob", lname: "The Builder", age: "old"};
var {fname, lname} = person;
assert(fname, person.fname) // true
assert(lname, person.lname) // true

and of course

// javascript being functional
function sqr(x) { return x * x; }
function doub(x) { return x + x; }
function add5(x) { return x + 5; }
function add(x, y) { return x + y; }

function boop(value) { 
  return function(fn) {
    return fn(value);
  }
}

[sqr, doub, add5, add.bind(null,1)].map(boop(5)); // [25, 10, 10, 6]
1 Like

I like the Prototypes, because it helps creating a method reference instead of duplicating in any object instances.

Also Closures, for keeping variables private.

It’s not a tidbit per se, but the fact that javascript is becoming more and more ubiquitous (read: necessary) is very exciting. In a world where technologies come and go with the seasons, js continues to grow, expand, take on new challenges, be used in new ways, etc. That’s rare.

A tidbit is it not :wink:

"use strict";

Such a powerful statement,with strict mode everyone will be on the same page and the code will be much cleaner.

I also like :

function a(){
   return (function(){return 5;})();    
   }

Closure :smiley:

var haveBook = Math.round(Math.random());
    function getBook() {
        return (haveBook !== 0) ? "Congrats!" : "Too bad.. next time";
    }
    console.log(getBook());

Ternary rocks…
Hello hello! I’d love to have this book, I’m thirsty for javascript!!

2 Likes

alert(JSON.stringify(YOUR_OBJECT_HERE, null, 4));
Just because people are still using IE8.

Jeremy Keith describes a neat way to manage breakpoints so that you don’t have to declare them in two places, once in CSS, and again in JavaScript. This involves a little bit of CSS, and a nice tidbit of JavaScript:

CSS

@media all and (min-width: 45em) {
    body:after {
        content: 'widescreen';
        display: none;
    }
}

JavaScript

if(window.getComputedStyle) {
    if (size.indexOf("widescreen") !=-1)
        // do something
    }
} else {
    // add default for IE8
}
2 Likes

I think a powerful thing is:

//.....
window.setTimeout(function async(){
//do something async
}, 0);
//....

The beautiful thing it’s the way how that goes:

  • call stack
  • web api (browser api) → trigger timer in background
  • finish current call stack
  • wait for render queue (if something in it) → event loop → process from callback queue
  • call stack - call async() callback
1 Like

My favorite javascript tidbit is:

console.log()

1 Like