228 Matching Annotations
  1. Last 7 days
  2. Mar 2020
    1. Let's replicate our inefficientSquare example, but this time we'll use our memoizer to cache results.

      Replication of a function with the use of memoizer (check the code below this annotation)

    2. The biggest problem with JSON.stringify is that it doesn't serialize certain inputs, like functions and Symbols (and anything you wouldn't find in JSON).

      Problem with JSON.stringify.

      This is why the previous code shouldn't be used in production

    3. Let's reason through our memoizer before we write any code.

      Operations performed by a memoizer:

      • Takes a reference to a function as an input
      • Returns a function (so it can be used as it normally would be)
      • Creates a cache of some sort to hold the results of previous function calls
      • Any future time calling the function, returns a cached result if it exists
      • If the cached value doesn't exist, calls the function and store that result in the cache

      Which is written as:

      // Takes a reference to a function
      const memoize = func => {
        // Creates a cache of results
        const results = {};
        // Returns a function
        return (...args) => {
          // Create a key for results cache
          const argsKey = JSON.stringify(args);
          // Only execute func if no cached value
          if (!results[argsKey]) {
            // Store function call result in cache
            results[argsKey] = func(...args);
          // Return cached value
          return results[argsKey];
    1. How do you leverage browser cache when Google’s very own Analytics.js has it’s expiry time set to 2 hours? How do you minimize DNS requests when Google advices you to copy their tracking code, linking to an externally hosted Javascript file?If that isn’t bad enough already, Google’s advice is to avoid hosting the JavaScript file locally. And why? To ensure you get access to new features and product updates.
    2. Why should I host analytics.js locally?The Complete Analytics Optimization Suite for WordPress gives you the best of both worlds. After activation it automagically downloads the latest version of analytics.js from Google’s servers, places the necessary tracking code in your WordPress theme’s header and keeps the local Javascript file up-to-date using an adjusted version of Matthew Horne’s update analytics script and wp_cron(). This way you can minimize DNS requests, leverage browser cache, track your visitors and still follow Google’s recommendation to use the latest features and product updates.
    1. Javascript, APIs and Markup — this stack is all about finding middleground from the chaos of SSR+SPA. It is about stepping back and asking yourself, what parts of my page change and what parts don’t change?

      JavaScript, APIs and Markup (JAM Stack) - middleground between SSR + SPA.


      • The parts that don’t change often are pre-rendered on the server and saved to static HTML files. Anything else is implemented in JS and run on the client using API calls.
      • Avoids too much data transfer (like the hydration data for SSR), therefore finds a good tradeoff to ship web content
      • Allows to leverage the power and cost of Content delivery networks (CDNs) to effectively serve your content
      • With serverless apps your APIs will never need a server to SSH into and manage
    1. TL;DR;

      Don't use:

      • No global vars.
      • Declare variables using "var".
      • Declare functions using "function" keyword.
      • Avoid use "for" in loops.
      • Array push, inmutability.
      • Class.
      • Use delete to remove a object atribute.
      • Avoid nested if.
      • else if.
      • Heavy nesting.
      • Avoid to add prototype to functions that could be used in a module.


      • Common code in functions, follow D.R.Y principle.
      • Shorcut notation.
      • Spread operator over Object.assign (airbnb 3.8).
      • Pascal case naming.
      • Modularize your code in modules.
      • const and let!.
      • Literal syntax for object creation (airbnb 3.1).
      • Computed property names when creating objects (airbnb 3.2).
      • Property value shorthand (airbnb 3.4).
      • Group your shorthand properties at the beginning of your objec (airbnb 3.5).
      • use the literal syntax for array creation (airnbnb 4.1).
      • Use array spreads ... to copy arrays. (airbnb 4.3).
      • use spreads ... instead of, Array.from. (airbnb 4.4).
      • Use return statements in array method callbacks (airbnb 4.7).
    2. Don’t use iterators, prefer js higher-order functions instead of for / for..in
      // bad
      const increasedByOne = [];
      for (let i = 0; i < numbers.length; i++) {
        increasedByOne.push(numbers[i] + 1);
      // good
      const increasedByOne = [];
      numbers.forEach((num) => {
        increasedByOne.push(num + 1);
    3. Ternaries should not be nested and generally be single line expressions.


      const foo = maybe1 > maybe2 ? 'bar' : maybeNull;


      // bad
      const foo = a ? a : b;
      const bar = c ? true : false;
      const baz = c ? false : true;
      // good
      const foo = a || b;
      const bar = !!c;
      const baz = !c;
    4. Use === and !== over == and !=.

      Bases on the Airbnb guide

    5. Use JSDOC https://jsdoc.app/about-getting-started.html format.

      Standardise your JavaScript comments:

      1. Use block comment
        /** This is a description of the foo function. */
        function foo() {
      2. Use JSDOC tag to describe a function: ```javascript /**
      • Represents a book.
      • @constructor
      • @param {string} title - The title of the book.
      • @param {string} author - The author of the book. */ function Book(title, author) { } ```
    6. When JavaScript encounters a line break without a semicolon, it uses a set of rules called Automatic Semicolon Insertion to determine whether or not it should regard that line break as the end of a statement, and (as the name implies) place a semicolon into your code before the line break if it thinks so. ASI contains a few eccentric behaviors, though, and your code will break if JavaScript misinterprets your line break.

      Better place a semicolon (;) in the right place and do not rely on the Automatic Semicolon Insertion


      const luke = {};
      const leia = {};
      [luke, leia].forEach((jedi) => {
        jedi.father = 'vader';


    7. Use uppercase only in constants.

      Uppercase for constants

      export const API_KEY = 'SOMEKEY';
    8. Use PascalCase only when naming constructors or classes.

      PascalCase for constructors and classes

      // good
      class User {
        constructor(options) {
          this.name = options.name;
      const good = new User({
        name: 'yup',
    9. Use camelCase when naming objects, functions, and instances.

      camelCase for objects, functions and instances

      const thisIsMyFuction() {}
    1. The combination of WordPress, React, Gatsby and GraphQL is just that - fun

      Intriguing combination of technologies.

      Keep an eye on the post author, who is going to discuss the technologies in the next writings

    1. In Python, when trying to do a dubious operation, you get an error pretty soon. In JavaScript… an undefined can fly through a few layers of abstraction, causing an error in a seemingly unrelated piece of code.

      Undefined nature of JavaScript can hide an error for a long time. For example,

      function add(a,b) { return + (a + b) }
      add('2', 2)

      will result in a number, but is it the same one?

    2. I recommend Airbnb style JavaScript style guide and Airbnb TypeScript)

      Recommended style guides from Airbnb for:

    3. I found that the overhead to use types in TypeScript is minimal (if any).

      In TypeScript, unlike in JS we need to specify the types:

    4. Write a new test and the result. If you want to make it REPL-like, instead of writing console.log(x.toString()) use expect(x.toString()).toBe('') and you will directly get the result.

      jest <--- interactive JavaScript (TypeScript and others too) testing framework. You can use it as a VS Code extension.

      Basically, instead of console.log(x.toString()), you can use except(x.toString()).toBe(''). Check this gif to understand it further

    5. ESLint does automatic code linting

      ESLint <--- pluggable JS linter:

      • mark things that are incorrect,
      • mark things that are unnecessary or risky (e.g. if (x = 5) { ... })
      • set a standard way of writing code
    1. map, filter and reduce can all operate independently, or be chained together

      map, filter, reduce

    2. During each loop of reduce, you can get result of the last loop, and the next element in the array Change the result, then return it for the next loop iteration When you're done, you have the completed collection

      reduce reduce

    3. This lets you transform each element into something new (or keep it the same) Types don't have to be the same: can return objects, string, numbers - anything!

      map map

    4. It loops over the elements, passing each one to a callback function You can return true to include that element in the new array, or false to exclude it

      filter filter

    5. So why are map, filter and reduce useful?

      Advantages of map, filter, reduce:

      • don't have to manually loop over array
      • chain together for short, straightforward array transformations
      • can reuse callback functions and compose them together
  3. Feb 2020
    1. k6 does not run in Node.js because it would perform poorly while running larger tests.Javascript is not generally well suited for high performance. It's a Go program - to achieve maximum performance - embedding a JavaScript runtime for running tests written in JavaScript.
  4. Jan 2020
    1. [...nodelist] will make an array of out of an object if the object is iterable. Array.from(nodelist) will make an array out of an object if the object is iterable or if the object is array-like (has .length and numeric props)
  5. Dec 2019
    1. Neutrino only babel-compiles first party source (the JSX -> JS transformation is handled by a babel plugin). It does this because even when using the module entry in package.json, it's expected that the provided file (and it's imports) still be JS and not in some other format - ie: the only difference from the content in main should be that it can use modules syntax (that is import and export rather than require etc).

      module version compared to main version:

      only difference from the content in main should be that it can use modules syntax (that is import and export rather than require etc).

      You can see the difference in this example: https://unpkg.com/browse/reactstrap@8.0.1/es/Alert.js ("module": "es/index.js": import) vs. https://unpkg.com/browse/reactstrap@8.0.1/lib/Alert.js ("main": "lib/index.js": require)

    1. esnext: source code using stage 4 features (or older), not transpiled, in ES modules. main continues to be used the same way. Its code can be generated from the untranspiled code. Most module use cases should be handleable via esnext. browser can be handled via an extended version of esnext (see next section).
    2. Input: JavaScript with stage 4 features or older, in ES modules. Output: whatever JavaScript runs best on the target platforms.
    1. This is a browser execution environment. It may provide additional built in objects exposed in the global namespace. It is a specialized execution environment which provides builtin capabilities beyond the base javascript language spec.
    2. This is a non-dom based javascript execution environment. It usually only contains the base javascript language spec libraries and objects along with modules to communicate with OS features (available through commonjs require).
    3. The use of a bundler to create a file(s) suitable for running on a client.
    4. It allows the module code (and subsequently dependants on the module) to not use preprocessor hacks, source code changes, or runtime detection hacks to identify which code is appropriate when creating a client bound package.
    5. The browser field is where the module author can hint to the bundler which elements (other modules or source files) need to be replaced when packaging.
    6. When a javascript module is prepared for use on a client there are two major concerns: certain features are already provided by the client, and certain features are not available. Features provided by a client can include http requests, websockets, dom manipulation. Features not available would include tcp sockets, system disk IO.
    7. You can simply prevent a module or file from being loaded into a bundle by specifying a value of false for any of the keys. This is useful if you know certain codepaths will not be executed client side but find it awkward to split up or change the code structure.
    1. Various test runners support using compiled webpack code to drive tests, but may be difficult to integrate with webpack, and Neutrino helps alleviate this
  6. Nov 2019
    1. const setRefs = useRef(new Map()).current; const { children } = props; return ( <div> {React.Children.map(children, child => { return React.cloneElement(child, { // v not innerRef ref: node => { console.log('imHere'); return !node ? setRefs.delete(child.key) : setRefs.set(child.key, node)

      Illustrates the importance of having unique keys when iterating over children, since that allows them to be used as unique keys in a Map.

    1. Reason compiles to JavaScript thanks to our partner project, BuckleScript, which compiles OCaml/Reason into readable JavaScript with smooth interop. Reason also compiles to fast, barebone assembly, thanks to OCaml itself.
    1. return class extends React.Component {

      Cool! anonymous/unnamed classes used here

    1. React guarantees that setState function identity is stable and won’t change on re-renders. This is why it’s safe to omit from the useEffect or useCallback dependency list.
    1. Since the checkbox is rendering an input I would work with it rather than focusing on the image. You could do something like this: const checkbox = getByTestId('checkbox-1234').querySelector('input[type="checkbox"]') expect(checkbox).toHaveProperty('checked', true)
    2. the way Material UI works is it renders a different SVG when the checkbox is clicked, and not changing the attributes or anything on the actual input element. So how do I actually test that the element is checked in line with the react-testing-library philosophy?

      These tags belong to entire page. This quote is just supporting evidence for the tags.

    1. Tests implementation details a bit (child component props received), but pretty good other than that.

      https://www.robinwieruch.de/react-testing-tutorial, for example, says that is reasonable to do:

      an integration test could verify that all necessary props are passed through from the tested component to a specific child component.

  7. developer.mozilla.org developer.mozilla.org
    1. Using with is not recommended, and is forbidden in ECMAScript 5 strict mode. The recommended alternative is to assign the object whose properties you want to access to a temporary variable.
    1. I don't recommend unit testing stateful components, or components with side-effects. Write functional tests for those, instead, because you'll need tests which describe the complete end-to-end flow, from user input, to back-end-services, and back to the UI. Those tests frequently duplicate any testing effort you would spend unit-testing stateful UI behaviors. You'd need to do a lot of mocking to properly unit test those kinds of components anyway, and that mocking may cover up problems with too much coupling in your component.
  8. Oct 2019
    1. "Element" SelectorsEach component has a data-reach-* attribute on the underlying DOM element that you can think of as the "element" for the component.
    1. There are many strings which I need to convert if not undefined. I could do as follows: { date1: date1 ? formatISODate(date1) : undefined, date2: date2 ? formatISODate(date2) : undefined ...
    1. Try to avoid mucking with native prototypes, including Array.prototype, if you don't know who will be consuming your code (3rd parties, coworkers, yourself at a later date, etc.). There are ways to safely extend prototypes (but not in all browsers) and there are ways to safely consume objects created from extended prototypes, but a better rule of thumb is to follow the Principle of Least Surprise and avoid these practices altogether.
    2. He's not messing with them he's extending them for Arrays.
  9. Sep 2019
    1. forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool. Early termination may be accomplished with:
    1. Object.fromEntries = arr => Object.assign({}, ...arr.map( ([k, v]) => ({[k]: v}) ));
    2. Using reduce and Object.keys As (1), in combination with Object.assign Using map and spread syntax instead of reduce Using Object.entries and Object.fromEntries
  10. Aug 2019
    1. The parentheses ( ... ) around the assignment statement are required when using object literal destructuring assignment without a declaration. {a, b} = {a: 1, b: 2} is not valid stand-alone syntax, as the {a, b} on the left-hand side is considered a block and not an object literal.
    2. Your ( ... ) expression needs to be preceded by a semicolon or it may be used to execute a function on the previous line.
  11. Jul 2019
    1. However using the proposed syntax it's easy to see how big components could have logic broken up into smaller reusable pieces, moved into separate files if necessary, leaving you with small, easy-to-understand functions and components.

      Benefits are evident and good, imho. A big improvement in code organization and separation of concerns.

      Just, I think the new syntax suffers from the loss of, as you said, that easy-to-understand-separation-by-type, that is appealing and clearer to newcomers and people that deal with pretty simple components. The component code is divided in three different sections (State, Computed, Methods) that are easy to scroll and to keep conceptually segregated.

      That's one appealing aspect for beginners, helping them to grab the main concepts and organization of Vue. Also helps giving some simpler view to who not too confident with JS and its patterns. With this "separation by function" the beginner is more disoriented since has to import state & computed as functions to place in specific points. Places that they need to know/remember, rather than just filling up the three object provided in module.exports (and I suppose there are packages that build a basic .vue template for you; maybe vue-cli itself too, that people get used to blindly use).

      So in the end the new syntax gives in my opinion a lot more power in modelling, but requires to accept some compromises with the somehow more verbose syntax (const everywhere; return & export providing private/public but necessarily longer to write) and with the slightly higher shadiness of its main concepts.

      Still, a good & efficient & clear documentation, as it was on Vuejs.org until today, will for sure easily compensate to these drawbacks and bring the most out of this new -more OOP- approach. For me also class could be use here, but I like trying to stay compatible using the prototypical approach (maybe also less overhead? Dunno, I'm not so deeply in the JS world).

      I am actually pretty curious to see how it is gonna evolve. And I am glad I didn't engage with Vue too much yet... 😜

  12. May 2019
    1. The document object gives access to the page content

      note: page content, not other functional areas of the browser. Read on to see other parts of the browser.

  13. Apr 2019
    1. So, if you are thinking of hiring JavaScript developers for your upcoming project, then there is no other time than now.

      So, if you are thinking of hiring JavaScript developers for your upcoming project, then there is no other time than now.

  14. Jan 2019
    1. “I see. You’ve been starting at AAAAAAA... and working up to ZZZZZZZZ....” “Exactly — though we use a special alphabet of our own. Modifying the electromatic typewriters to deal with this is, of course, trivial. A rather more interesting problem is that of devising suitable circuits to eliminate ridiculous combinations. For example, no letter must occur more than three times in succession.” “Three? Surely you mean two.” “Three is correct: I am afraid it would take too long to explain why, even if you understood our language.”

      Andrew Oakley actually wrote a Javascript program to do exactly what the monk was asking Dr. Wagner on the day that Arthur C. Clarke died (March 19, 2008). The site of course has a disclaimer if you decide to run the program to completion: "USE OF THIS PROGRAM IS AT YOUR OWN RISK. I WILL NOT ACCEPT ANY LIABILITY FOR THE CONSEQUENCES SHOULD YOU ALLOW THIS PROGRAM TO RUN TO COMPLETION." See: http://www.aoakley.com/articles/2008-03-19.php