386 Matching Annotations
  1. Last 7 days
    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]; } }
      
  2. Oct 2020
    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.
  3. 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.
  4. 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);
          }
      }
      
  5. 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
  6. 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.
  7. 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.

  8. 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
  9. 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.