Thursday, November 9, 2023

Understanding the implications of return await in ecmascript

In ECMAScript, an async function always wraps the returned value in a Promise. If you return a value, it's equivalent to returning Promise.resolve(value). If you throw an error, it's akin to returning Promise.reject(error). When you await a Promise, the function's execution is paused until the Promise is settled.

Consider the following code inside an async function:

javascript
return await someAsyncFunction();

This will pause the execution of the current function until someAsyncFunction() resolves, and then immediately return the resolved value. However, since async functions automatically wrap returned values in Promises, you can simply write:

javascript
return someAsyncFunction();

In this case, someAsyncFunction() is returned directly. The Promise returned by someAsyncFunction() will be returned by your function as-is. The JavaScript engine doesn't need to create an additional microtask to resolve the await, which it would do in the return await case. Here's why you might see a performance difference:

  1. Microtask Queue Management: Every time you await a Promise, the engine adds a microtask to the queue for when the Promise resolves. Using return await adds an unnecessary microtask because you could return the Promise directly, and the calling code will await it anyway.

  2. Stack Trace Generation: When you use await, the engine keeps track of the function from which it was called for the purpose of generating stack traces if an error is thrown. This can add overhead compared to returning a Promise directly, which doesn't require the engine to manage the stack in the same way.

  3. Optimization: JavaScript engines can optimize return someAsyncFunction(); more effectively than return await someAsyncFunction(); because the former has less complexity for the engine to analyze and optimize.

The performance penalty of return await is generally quite small and may not be noticeable in everyday code. However, it's a good practice to avoid unnecessary await for the reasons above, especially in performance-critical code or in loops.

Here’s an example where return await does make sense and has no performance penalty:

javascript
async function foo() { try { return await someAsyncFunction(); } catch (error) { // Error handling } }

In the example above, return await is necessary to catch any promise rejections from someAsyncFunction() within the foo function's try block. Without await, a rejected promise would not be caught by try/catch, and the error handling would not work as intended.

Thursday, March 9, 2023

From CommonJS/Require to ES modules the easy way

Introduction

When Node.js was first conceived, jQuery as a community; had embraced the AMD pattern and RequireJS in particular. Node.js was designed to run JavaScript code outside of a web browser, and as such, it needed a module system that was optimized for server-side development. CommonJS was the solution that was chosen because it fit the requirements of the Node.js ecosystem at the time.. CommonJS was the resulting solution and has been used in Node.js since v0.x. 

Meanwhile, the browser has continued to evolve sought to address the need that RequireJS was filling. With ECMAScript 6 (ES6), ECMAScript modules (ESM) were introduced.

ESM is a newer module format that is part of the ECMAScript language specification, and it provides a standard way to define modules in JavaScript. ESM provides a number of benefits over CommonJS, including better performance, improved compatibility with tooling and bundlers, and better support for static analysis and tree-shaking.

Since the release of ECMAScript 6, many JavaScript environments have added support for ESM, including Node.js, web browsers, and many other runtimes.

FAQ First

1. What is CommonJS?

CommonJS module system is the default module system within the NodeJS ecosystem. CommonJS modules are the original way to package JavaScript code for Node.js. In terms of the loading paradigm for CommonJS, modules are loaded synchronously and are processed in the same order that the JavaScript runtime locates them. CommonJS provides require()


2. What are ESM?

The ES module usage format is the official standard to write JavaScript for maximum reusability and is what most web browsers natively support and Node.JS has fully supported since 12.x (experimental support as early as 9.x.)


3. What are major difference between CommonJS and ESM?

  • CommonJS is synchronous whereas ES is asynchronous
  • CommonJS supports only runtime resolution whereas ES supports both parse time and runtime
  • ESM support interoperability whereas CommonJS do not
  • CommonJS is the original standard in Node.js whereas ES recently achieved stable support and has been in in browsers for 5+ years
  • Common JS uses require() and ESM uses import export

4. What are the benefits of CommonJS?

CommonJS is the default standard and is supported in all Node.js versions. It is resolved at Runtime and has a wide amount of Dev support since it has been there since the beginning of Node.JS


5. Does Node.js use CommonJS?

Yes, CommonJS was the default Standard for module inclusion. 


6. Does Node.js use ES Modules (ESM)?

Yes, ESM is fully supported since Node.js 12.x


7. Is CommonJS going away?

There is no sunset date on CommonJS, but it's not native to ecmascript as ESM is so it might be expected to be deprecated at some point in favor of ESM and, it is worth noting that many developers are now migrating to ESM, especially for new projects or where the benefits of ESM outweigh the costs of migration.


Commonjs/Requirejs/AMD pattern

function foo() {}

modules.exports = foo;

Use

foo = require('foo');


ECMAscript modules (ESM/modules)

export function foo() {}

Use

// An https url can also be provided
import { foo } from "foo.mjs";

For some advanced tricks, check out Data URLs.


Package.json changes and file extensions

When using require('foo'); we are depending on CommonJS, which is well-established in Node.js since v0.1.0. As of node v9.x, it has been possible to enable an experimental flag to begin using ESM. As of Node.js v12.x, ESM are natively supported. The overall migration path from CommonJS to ESM can take multiple forms. To provide compatibility and keep longterm changes to a minimum, the following behaviors exist:
  • .js file extension is assumed to implement CommonJS
  • .mjs file extension is assumed to implement ESM
  • .cjs file extension is assumed to implement CommonJS
  • package.js can include { "type": "module" } to indicate .js file extension will contain ESM. With this, there is no longer a need to use the .mjs extension
  • Node can be run with --experimental-specifier-resolution=node to tell node to support CommonJS and ESM BOTH in .js files

ESLint

If you embrace ESlint, know that definitions must be based on es2021 (es12) or newer. Previous ecmascript versions require other approaches (like --experimental node.js flags.)


Bonus

Starting from Node.js 14.13.0 and higher, it's possible to import CommonJS modules using the ES module syntax (import/export). In other words, you can use the import statement to import objects from a CommonJS module that exports using module.exports.

For example, if you have a CommonJS module foo.js that exports an object like this: 

module.exports = { a: 1, b: 2, c: 3 };

You can import this object using the ES module syntax like this:

import foo from './foo.js'; console.log(foo.a); // Output: 1

Note that you need to use a file extension of .mjs for the importing file (see above) if you're using ECMAScript modules. However, if you prefer to use the .js file extension for both CommonJS and ECMAScript modules, you can add "type": "module" to your package.json file OR run Node.js with --experimental-specifier-resolution=node 


The FAQ and other bits where borrowed from:

https://www.knowledgehut.com/blog/web-development/commonjs-vs-es-modules

Thursday, February 2, 2023

Reasons NOT to use ESlint (sarcasm)

If you're looking to add chaos and confusion to your coding workflow, look no further than ESLint. This tool is designed to ensure that your code meets a certain set of standards and is free of any potential errors. But why would anyone want to use such a bothersome program? Here are just a few of the many reasons why you should avoid ESLint at all costs. Who needs organized and consistent code anyway? Who needs to save time by automatically catching syntax and formatting errors before they even reach the browser? And let's not forget about the joy of scrolling through hundreds of lines of messy, unreadable code. Who needs to be productive and efficient, right?

First of all, who has time to waste on pesky linting errors? It's much more fun to spend your valuable coding time debugging runtime issues. Not to mention, the rules that ESLint forces you to abide by are often arbitrary and outdated. Who wants to spend their days writing code that conforms to the stylistic preferences of others? Furthermore, the amount of time it takes to even set up ESLint can be a bit overwhelming. It might seem like a small task, but it can quickly become tedious and time-consuming.

Second, ESLint can be incredibly tedious to work with. It often requires you to spend hours hunting down small typos and other minor errors that could be easily overlooked. Not to mention, the linting rules can be difficult to decipher and often require you to make numerous adjustments to your code in order to comply. This can be incredibly time-consuming and ultimately leave you with code that doesn’t even meet the standards that ESLint was meant to enforce. Clearly, using ESLint is for the weak-hearted. It's for those who value productivity, consistency, and a well-organized codebase. But if you're like me, you'd much rather spend hours trying to decipher and fix code that could have been caught by a simple linter. So go ahead, do yourself a favor, and steer clear of the temptations of ESLint. Your code will thank you for it.

The final nail in the coffin is the fact that ESLint often introduces unexpected bugs into your code. Since the program is designed to catch coding errors, it can be difficult to figure out why an error is occurring, especially if you’re unfamiliar with the program. Furthermore, you can’t even trust ESLint to catch all of the errors in your code. This means that you may find yourself spending even more time troubleshooting and hunting down errors that the program missed. So, why bother using it in the first place? Furthermore, who needs the peace of mind that comes with knowing your code adheres to a standardized style guide, or the ability to easily catch potential bugs and security vulnerabilities before they become a problem? Who wants to work in a team where everyone follows the same code conventions, making collaboration smoother and conflicts less frequent?


In conclusion, ESLint is clearly not worth the headache. If you value your short-term sanity, you should avoid it. In the unlikely chance you like to sleep soundly, knowing your code is as solid as possible, you could look into it. What if sanity is overrated though?


Followers