My notes on Secrets of the JavaScript Ninja. The second edition, which includes new features of ES6 and ES7, was just released on August 2016. I figured it would be a great book to have for enhancing JavaScript skills.

Invalid HTML in <head>

I never really thought about this as I never had put any HTML tags in head other than those valid ones, like title, link and meta. It turns out that the browser silently fixes it by constructing the correct DOM, in which the paragraph element is placed at the very beginning of the body element.

Two phases of the execution of client-side applications

Page building

  1. Building the DOM from HTML.
  2. Executing JavaScript code when script nodes are encountered.

Event handling

Two ways to register event handlers:

// 1. Assign a function to special properties of an object
window.onload = function() {}

// 2. Use the build-in `addEventListener` method on an HTML element
document.body.addEventListener('mousemove', () => {})

The second approach is preferred because it allows multiple event listeners added to the element, whereas assigning a function to the property can be overridden.

Event types:

  • Browser events (page finished loading…)
  • Network events (Ajax events, server-side events…)
  • User events (mouse clicks, key pressed…)
  • Timer events (timeout expires, interval fires…)

Generated events are pushed into the event queue and executed one at a time in the order in which they occurred.

Immediate functions

Several ways to invoke a function expression immediately:

// Parentheses around function expressions
(function (){})()
// Or alternatively (though less used)
(function (){}())

// Unary operators +, -, ! and ~

Why do we need need those parentheses (or unary operators) to immediately call our function expression? That’s because these syntax allows the JavaScript parser being able to identify them as function expressions instead of function declarations. If we leave out the parentheses, function(){}() will be treated as a function declaration as it starts with the keyword function.