67 Matching Annotations
  1. Jul 2018
    1. for (var i=0; i < 5; i++) { (function () { var i2 = i; // copy current i result.push(function () { return i2 }); }()); }

      2.3 Note that both let and const are block-scoped. You can replace an IIFE that looks like:

      // bad
      for (var i=0; i < 5; i++) {
          (function () {
              var i2 = i; // copy current i
              result.push(function () { return i2 });
          }());
      }
      

      with just:

      // good
      for (let i=0; i < 5; i++) {
          // copy current i
          const i2 = i;
          result.push(() => i2);
      }
      
    2. This section does not fully explain how JavaScript inheritance works, but it shows you a simple pattern to get you started. Consult Chapter 17 if you want to know more.In addition to being “real” functions and methods, functions play another role in JavaScript: they become constructors—factories for objects—if invoked via the new operator. Constructors are thus a rough analog to classes in other languages. By convention, the names of constructors start with capital letters. For example:// Set up instance data function Point(x, y) { this.x = x; this.y = y; } // Methods Point.prototype.dist = function () { return Math.sqrt(this.x*this.x + this.y*this.y); };We can see that a constructor has two parts. First, the function Point sets up the instance data. Second, the property Point.prototype contains an object with the methods. The former data is specific to each instance, while the latter data is shared among all instances.To use Point, we invoke it via the new operator:> var p = new Point(3, 5); > p.x 3 > p.dist() 5.830951894845301p is an instance of Point:> p instanceof Point true

      9.1 Always use class. Avoid manipulating prototype directly.

    3. Binary logical operators: && (And), || (Or)

      Note that these operators do not necessarily produce booleans, as described below, && returns the first Falsy operand and || returns the last Truthy operand, short-circuited.

    4. Boolean(), called as a function, converts its parameter to a boolean. You can use it to test how a value is interpreted:> Boolean(undefined) false > Boolean(0) false > Boolean(3) true > Boolean({}) // empty object true > Boolean([]) // empty array true

      22.6 Booleans