All I Want for Christmas: Effective JavaScript — Book Giveaway

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

console.table() is a good one, too.
It logs any supplied data using a tabular layout.

console.table([{a:1, b:2, c:3}, {a:"foo", b:false, c:undefined}]);
console.table([[1,2,3], [2,3,4]]);
2 Likes

I don’t like the ‘dangling balls’ as Crockford puts it lol

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.