784 Matching Annotations
  1. Oct 2020
    1. for (var member in myObject) delete myObject[member]; ...would seem to be pretty effective in cleaning the object in one line of code

      But checking hasOwnProperty is probably better/safer idea:

      for (var prop in obj) { if (obj.hasOwnProperty(prop)) { delete obj[prop]; } }
      
    1. Another example:

      const expensiveOperation = async (value) => {
        // return Promise.resolve(value)
          // console.log('value:', value)
          await sleep(1000)
          console.log('expensiveOperation: value:', value, 'finished')
          return value
      }
      
      var expensiveOperationDebounce = debounce(expensiveOperation, 100);
      
      // for (let num of [1, 2]) {
      //   expensiveOperationDebounce(num).then(value => {
      //     console.log(value)
      //   })
      // }
      (async () => { await sleep(0   ); console.log(await expensiveOperationDebounce(1)) })();
      (async () => { await sleep(200 ); console.log(await expensiveOperationDebounce(2)) })();
      (async () => { await sleep(1300); console.log(await expensiveOperationDebounce(3)) })();
      // setTimeout(async () => {
      //   console.log(await expensiveOperationDebounce(3))
      // }, 1300)
      

      Outputs: 1, 2, 3

      Why, if I change it to:

      (async () => { await sleep(0   ); console.log(await expensiveOperationDebounce(1)) })();
      (async () => { await sleep(200 ); console.log(await expensiveOperationDebounce(2)) })();
      (async () => { await sleep(1100); console.log(await expensiveOperationDebounce(3)) })();
      

      Does it only output 2, 3?

    1. JavaScript is, of course, a dynamic language that allows you to add and remove objects and their members at any point in time. For many, this is precisely why they enjoy the language: there are very few constraints imposed by the language.
    1. You can set options.params to a POJO as shown above, or to an instance of the JavaScript's built-in URLSearchParams class. const params = new URLSearchParams([['answer', 42]]); const res = await axios.get('https://httpbin.org/get', { params });
    1. In contrast, an object's actual prototype (obtained with Object.getPrototypeOf) is the real and only definition of an object's nature -- even in the possible case that its prototype has been changed after creation (either though the spec compliant Object.setPrototypeOf or by changing the commonly implemented __proto__ property).
    1. Checking if an object is a POJO can be somewhat tricky and depends on whether you consider objects created using Object.create(null) to be POJOs. The safest way is using the Object.getPrototypeOf() function and comparing the object's prototype.
    1. mixing the turing complete of javascript with the markup of HTML eliminates the readability of JSX so that it is actually harder to parse than a solution like hyperscript
    2. If the react cargo cult didn't have the JSX cowpath paved for them and acclimated to describing their app interface with vanilla javascript, they'd cargo cult around that. It's really about the path of least resistance and familiarity.
    3. hyperscript is much simpler to refactor and DRY up your code than with JSX, because, being vanilla javascript, its easier to work with variable assignment, loops and conditionals.
    4. Don't think so; template strings solve the problem JSX tries to tackle without forking the language.
    1. My proposal is that we solve this by treating a static key prop as different from one provided through spread. I think that as a second step we might want to even give separate syntax such as:
    1. trusktr herman willems • 2 years ago Haha. Maybe React should focus on a template-string syntax and follow standards (and provide options for pre-compiling in Webpack, etc).

    2. To suggest template literals cover the level of abstraction that JSX has to offer is just dumb. They're great and all, but c'mon now...

    1. However, this would lead to further divergence. Tooling that is built around the assumptions imposed by template literals wouldn't work. It would undermine the meaning of template literals. It would be necessary to define how JSX behaves within the rest of the ECMAScript grammar within the template literal anyway.
    2. Template literals work well for long embedded DSLs. Unfortunately the syntax noise is substantial when you exit in and out of embedded arbitrary ECMAScript expressions with identifiers in scope.
    3. ECMAScript 6th Edition (ECMA-262) introduces template literals which are intended to be used for embedding DSL in ECMAScript.
    4. Why not Template Literals?
    1. This is valid javascript! Or harmony or es6 or whatever, but importantly, it's not happening outside the js environment. This also allows us to use our standard tooling: the traceur compiler knows how to turn jsx`<div>Hello</div>`; into the equivalent browser compatible es3, and hence we can use anything the traceur compile accepts!
    1. IMO svelte does have a responsibility to teach/demo the basics of "functional javascript" probably as a docs/tutorial/demos chapter on "the power of javascript expressions"
    1. use Xstate which offers a finite state machine that adheres to the SCXML spec­i­fi­ca­tion and provides a lot of extra goodness, including vi­su­al­iza­tion tools, test helpers and much more
    1. the function you pass to the find method is called a predicate. The predicate here defines a boolean outcome based on conditions defined in the function itself, so that the find method can determine which value to find.
    1. perhaps, imo this would make more sense. but it would slow down Parcel significantly as packages who don't have a browserslist or something similar will all get compiled (and most packages actually do target commonjs, which makes this prob not such a good idea). Which unfortunately is way too many packages. It would be great if tools like babel actually enforced a similar pattern to Parcel and use browserlist file or package.json instead of allowing defining target env in babel. Or at least not encourage it.
  2. Sep 2020
    1. But we face our own hostile environment: underpowered devices, poor network connections, and the complexity inherent in front-end engineering.
    1. Your problem is that you were returning the rejected loginDaoCall, not the promise where the error was already handled. loginApi.login(user, password) did indeed return a rejected promise, and even while that was handled in another branch, the promise returned by the further .then() does also get rejected and was not handled.
    2. // LoginApi.js return loginDao.login(username, password).then(function (res) { store.dispatch(loginSuccess()); log.log("[loginApi.login] END"); return true; }, function (err) { store.dispatch(loginFail()); errorUtils.dispatchErrorWithTimeout(errorLogin); log.log(err); return false; }); // never supposed to reject
    1. This treatment of thenables allows promise implementations to interoperate, as long as they expose a Promises/A+-compliant then method. It also allows Promises/A+ implementations to “assimilate” nonconformant implementations with reasonable then methods.
    2. the promise specification explicitly does not make a distinction
    1. I love how they have this example with plain JS to show how slim and simple it can be even when not using react and react-final-form. It demystifies things so you can see how it works and how it would be if not using React (which in turn helps you appreciate what react/react-final-form do for you).

    1. If you need to call the function repeatedly, this is much, much faster than using eval.
    2. Some modules, like events or util, are built in to Node.js. If you want to include those (for example, so that your bundle runs in the browser), you may need to include rollup-plugin-node-polyfills.
    1. If you've followed React's guide, you've installed react from npm. You can teach Rollup how to find this package within your project's node_modules directory using the rollup-plugin-node-resolve plugin. Since React exports a CommonJS module, you'll also need to convert that into an ES6 module using the rollup-plugin-commonjs plugin.
    1. This isn't really a bug, because if you have an async function that returns a function, it doesn't really return a function - it returns a promise. I don't remember whether the Svelte internals currently check for the onMount callback's return being a function or whether they check for it being truthy. Maybe there's some adjustment to be made there.
    1. The lack of spread continues to be a big pain for me, adding lots of difficult-to-maintain cruft in my components. Having to maintain a list of all possible attributes that I might ever need to pass through a component is causing me a lot of friction in my most composable components.
    1. By default, in order to allow inline fat-arrow validation functions, the field will not rerender if you change your validation function to an alternate function that has a different behavior. If you need your field to rerender with a new validation function, you will need to update another prop on the Field, such as key
    1. function* enumerate(iterable) { let i = 0; for (const x of iterable) { yield [i, x]; i++; } } for (const [i, obj] of enumerate(myArray)) { console.log(i, obj); }
    2. for (let [index, val] of array.entries())
    3. Note that Array.entries() returns an iterator, which is what allows it to work in the for-of loop; don't confuse this with Object.entries(), which returns an array of key-value pairs.
    4. Object.keys(obj).forEach could work, but it only includes own properties; for…in includes enumerable properties anywhere on the prototype chain.
    1. Here we store the three Promise objects in variables, which has the effect of setting off their associated processes all running simultaneously. Next, we await their results — because the promises all started processing at essentially the same time, the promises will all fulfill at the same time
    1. The value attribute of an input element or its children option elements must not be set with spread attributes when using bind:group or bind:checked. Svelte needs to be able to see the element's value directly in the markup in these cases so that it can link it to the bound variable.
    1. Rest syntax looks exactly like spread syntax. In a way, rest syntax is the opposite of spread syntax. Spread syntax "expands" an array into its elements, while rest syntax collects multiple elements and "condenses" them into a single element.
    1. Note that to use the this context the test function must be a function expression (function test(value) {}), not an arrow function, since arrow functions have lexical context.
  3. Aug 2020
    1. find every email on a web page that you're on. The big kahuna - this works for every website. Inject it into a site with Chrome DevTools (more here)

      Use this code below to find every e-mail on a webpage:

      var elems = document.body.getElementsByTagName("*");
      var re = new RegExp("(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)");
      for (var i = 0; i < elems.length; i++) {
          if (re.test(elems[i].innerHTML)) {
              console.log(elems[i].innerHTML);
          }
      }
      
  4. Jul 2020
    1. the umbrella term "JavaScript" as understood in a web browser context contains several very different elements. One of them is the core language (ECMAScript), another is the collection of the Web APIs, including the DOM (Document Object Model)
    1. name provided to a function expression as above is only available to the function's own scope
    2. supports functional programming — because they are objects, functions may be stored in variables and passed around like any other object
    3. most common host environment is the browser, but JavaScript interpreters can also be found in a huge list of other places
  5. Jun 2020
    1. What would be nice is if JavaScript had a built-in way to do what I can do in Ruby with:

      > I18n.interpolate('Hi, %{name}', name: 'Fred')
      => "Hi, Fred"
      

      But to be fair, I18n comes from i18n library, so JS could just as easily (and I'm sure does) have a library that does the same thing.

      Update: Actually, you can do this in plain Ruby (so why do we even need I18n.interpolate?):

      main > "Hi, %{name}" % {name: 'Fred'}
      => "Hi, Fred"
      
      main > ? String#%
      
      From: string.c (C Method):
      Owner: String
      Visibility: public
      Signature: %(arg1)
      Number of lines: 9
      
      Format---Uses str as a format specification, and returns the result
      of applying it to arg. If the format specification contains more than
      one substitution, then arg must be an Array or Hash
      containing the values to be substituted. See Kernel::sprintf for
      details of the format string.
      
         "%05d" % 123                              #=> "00123"
         "%-5s: %016x" % [ "ID", self.object_id ]  #=> "ID   : 00002b054ec93168"
         "foo = %{foo}" % { :foo => 'bar' }        #=> "foo = bar"
      

      I guess that built-in version is fine for simple cases. You only need to use I18n.translate if you need its more advanced features like I18n.config.missing_interpolation_argument_handler.

    2. When you hear there's something called "template strings" coming to JavaScript, it's natural to assume it's a built-in template library, like Mustache. It isn't. It's mainly just string interpolation and multiline strings for JS. I think this is going to be a common misconception for a while, though.
  6. May 2020
    1. localForage is a JavaScript library that improves the offline experience of your web app by using an asynchronous data store with a simple, localStorage-like API. It allows developers to store many types of data instead of just strings.
    1. This starter takes advantage of Typescript and Emotion. This is a personal choice, and I'd encourage you to give it a shot. If you're interested in using plain ES6 and regular scss styling, see release v1 of this library.
    1. There’s no need for nasty repetition in ES6!… // ES6 code const a = 1, b = 2, c = 3; obj = { a b c }; // obj.a = 1, obj.b = 2, obj.c = 3

      ES6 way of creating an object from variables .

    2. // ES5-compatible code var myObject = { prop1: 'hello', prop2: 'world', output: function() { console.log(this.prop1 + ' ' + this.prop2); } }; myObject.output(); // hello world

      Creating an object.

  7. developer.mozilla.org developer.mozilla.org
    1. The promises of a chain are nested like Russian dolls, but get popped like the top of a stack.
    2. Similarly, .catch() is really just a .then() without a slot for handleFulfilled.
    3. in the absence of an immediate need, it is simpler to leave out error handling until a final .catch() statement.
    4. Handling a rejected promise too early has consequences further down the promise chain.   Sometimes there is no choice, because an error must be handled immediately.
    1. Mozilla does not permit extensions distributed through https://addons.mozilla.org/ to load external scripts. Mozilla does allow extensions to be externally distributed, but https://addons.mozilla.org/ is how most people discover extensions. The are still concerns: Google and Microsoft do not grant permission for others to distribute their "widget" scripts. Google's and Microsoft's "widget" scripts are minified. This prevents Mozilla's reviewers from being able to easily evaluate the code that is being distributed. Mozilla can reject an extension for this. Even if an extension author self-distributes, Mozilla can request the source code for the extension and halt its distribution for the same reason.

      Maybe not technically a catch-22/chicken-and-egg problem, but what is a better name for this logical/dependency problem?

    1. Now, a couple of years later, my guidelines for JS are:

      Advices on using JavaScript from a long time programmer:

      1. Use TypeScript instead.
      2. Push as much logic to the server as possible
      3. Use a framework like Vue or React if you need front interactivity
      4. Don't skip unit tests
  8. Apr 2020
    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)
      add('2', 2)
      

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

    2. 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:

    3. 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
    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. I recommend Airbnb style JavaScript style guide and Airbnb TypeScript)

      Recommended style guides from Airbnb for:

    1. The “universal” label that has been slapped on to it is superfluous, but it does have its merits. Now that we have a commonly known term to refer to environment agnostic JavaScript code, it allows library authors to list it as a feature and be fashionable doing it. I’m happy with the term “universal” being fashionable because it makes developers think about their dependencies on the runtime environment. In the end this will help the JavaScript ecosystem mature and allow libraries to be used everywhere.
    2. The “universal” label that has been slapped on to it is superfluous
    3. Running the same code in the browser and on the server in order to avoid code duplication is a very different problem. It is simply a matter of good development practices to avoid code duplication. This however is not limited to isomorphic applications. A utility library such as Lodash is “universal”, but has nothing to do with isomorphism. Sharing code between environments does not give you an isomorphic application. What we’re referring to with Universal JavaScript is simply the fact that it is JavaScript code which is environment agnostic. It can run anywhere. In fact most JavaScript code will run fine on any JavaScript platform.
    4. Isomorphism itself is not purely a JavaScript thing. You can also build an isomorphic application in Dart or even use two different languages/stacks to render the same result. In fact there are many “isomorphic” applications which render a full HTML document on the server using PHP, Java or Ruby and use JavaScript and AJAX to create a rich user experience in the browser. This was the way things were done before the rise of Single Page Applications. The only real reason isomorphism is tied to JavaScript is because it’s the only language widely supported in the browser, and so at least part of the whole thing will use JavaScript. There’s no such thing as Isomorphic JavaScript, only isomorphic applications.
    1. Maybe we should distinguish between: The technique of asssembling pages on either client or server. Here, “isomorphic” and “full stack” (as proposed by Rodrigo Medeiros) seem good choices. JavaScript that runs in all (or most) JavaScript environments, especially browsers and Node.js. Here, “universal” seems a good choice.
    1. 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];
        };
      };
      
    2. 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)

    3. 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

    1. Use camelCase when naming objects, functions, and instances.

      camelCase for objects, functions and instances

      const thisIsMyFuction() {}
      
    2. 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',
      });
      
    3. Use uppercase only in constants.

      Uppercase for constants

      export const API_KEY = 'SOMEKEY';
      
    1. What is a Function Expression?A JavaScript function can also be defined using an expression.A function expression can be stored in a variable:var x = function (a, b) {return a * b};After a function expression has been stored in a variable, the variable can be used as a function. Functions stored in variables do not need function names. They are always invoked (called) using the variable name.

      Test question: What is function expression?

    1. Writing an async function is quite simple. You just need to add the async keyword prior to function:

      Test question: What is the syntax of async function?

    1. Using objects as keys is one of most notable and important Map features.

      Test question: What is one of the most notable and important Map features?

    2. Map is a collection of keyed data items, just like an Object. But the main difference is that Map allows keys of any type.

      Test question: What is the difference between Map and Object in JavaScript?

  9. javascript.info javascript.info
    1. he basic syntax is: let promise = fetch(url, [options])

      Test question: What s the basic syntax of fetch(); ?

    1. document.addEventListener("click", myFunction);function myFunction() {  document.getElementById("demo").innerHTML = "Hello World"; }

      document.addEventListener() - Reference to the external function.

    2. document.addEventListener(event, function, useCapture)

      Test question: What is the syntax of element.addEventListener() ?

    1. JSON syntax is basically considered as a subset of JavaScript syntax;

      Test question: What is JSON syntax part of?

  10. developer.mozilla.org developer.mozilla.org
    1. Never use eval()! eval() is a dangerous function, which executes the code it's passed with the privileges of the caller.

      Testing question: Should you ever use eval()?

    1. 对象属性的命名规则 通过[]操作符为对象添加属性时,属性名称可以是任何字符串(包括只包含空格的字符串和空字符串); 通过.操作符为对象添加属性时,属性名称必须是合法的标识符名称; 如果属性名包含非法的标识符字符,则只能采用obj[“propertyName”]的形式; 如果属性名是合法的标识符,读取时即可以采用obj.propertyName,也可以采用obj[“propertyName”]的形式;

      除此之外,根据下面的介绍,也可以用数字和布尔值作为属性名,但会自动转换为字符串。

    1. We really only need to test that the button gets rendered at all (we don’t care about what the label says — it may say different things in different languages, depending on user locale settings). We do want to make sure that the correct number of clicks gets displayed

      An example of how to think about tests. Also asserting against text that's variable isn't very useful.

    2. It’s still a good idea to keep your code in three different buckets, and keep these buckets isolated from each other:Display/UI ComponentsProgram logic/business rules — the stuff that deals with the problem you’re solving for the user.Side effects (I/O, network, disk, etc.)

      How do I organize my code like this? What's the directory structure look like.

    1. Any JavaScript style guide that is up-to-date for ES6 is going to cover nearly all TypeScript constructs except for type annotations, so I would start with your favorite JS style and decide on what you want the rules for type annotations to be

      可惜这个问题被关了。因此显得有点老。不过他的建议也不错。使用用JS的风格。

  11. Mar 2020
    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.

      Advantages:

      • 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.

      Use:

      • 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.

      e.g.

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

      Also:

      // 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

      e.g.

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

      ```

    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. 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
  12. 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.
  13. 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)
  14. 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.