DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,673 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for Features In Nodejs that you might have missed! πŸͺ
Ren Hiyama
Ren Hiyama

Posted on

Features In Nodejs that you might have missed! πŸͺ

Hey there, it's your dev Ren again! Thanks to everyone who read my last week's post on Make it Short - Make it Better and if you haven't, make sure to check it out!
Anyways let's get started!

Let's start


1. Top Level Await

It's finally here! We can now directly use this:

import fetch from "node-fetch";
let res = await fetch("https://example.com");
Enter fullscreen mode Exit fullscreen mode

Cheers 🍻! We previously had to wrap them inside a async function like this:

import fetch from "node-fetch";
(async()=>{
let res = await fetch("https://example.com");
})();
Enter fullscreen mode Exit fullscreen mode

2. Did you know Dynamic Imports existed?

They are a live saver in some cases, because you can't execute import x from "y" inside a function or a scope. You just need to use the dynamic imports version instead like this:

let x = await import("y");
Enter fullscreen mode Exit fullscreen mode

Important Note: Dynamic Imports have a downside as well, and I would suggest writing or using a custom Import function (like I do) that fixes some of the problems it has... For example,

import x from "y"
console.log(x());
Enter fullscreen mode Exit fullscreen mode

y.js file:

export default ()=>{return "hi"};
Enter fullscreen mode Exit fullscreen mode

While the first one works, this code won't:

let x = await import("y");
console.log(x());
Enter fullscreen mode Exit fullscreen mode

Instead you need to use console.log(x.default());
Or a better version:

let x = (await import("y")).default;
Enter fullscreen mode Exit fullscreen mode

But I would suggest to my own version of Imports, which you can easily use by this:

npm i reejs
Enter fullscreen mode Exit fullscreen mode

Now Initialize it:

import Import from "reejs/import.js";
globalThis.Import = Import; //optional; saves you from importing it in every file πŸ™ƒ
let x = await Import("y");
console.log(x()); //works!
Enter fullscreen mode Exit fullscreen mode

Basically it imports the same dependency/file, and runs a loop on it to get all the properties and save it in a new object, and make default work just like static imports do. (Not to mention my Import function even supports URL Imports on Node v16 incase you wanna try it out! πŸ˜‰)


3. Use Underscores with Integers for extra readability!

Instead of using this:

let num = 1000000000;
Enter fullscreen mode Exit fullscreen mode

You can now use:

let num = 1_000_000_000;
Enter fullscreen mode Exit fullscreen mode

God who doesn't love an extra readability? I do atleast.


4. Weak References (So you can scream on Garbage Collector)

WeakRef stands for Weak References. It allows you to create a weak reference to an object. A weak reference to an object is a reference that does not prevent the object from being reclaimed by the garbage collector.

The primary use of Weak Reference is to implement caches or mappings of large objects. Where it’s desired that a large object is not kept alive solely because it appears in a cache or mapping.

For example:

const obj = {name: "Ren", lastname: "Hiyama"};
const refObj = new WeakRef(obj);
Enter fullscreen mode Exit fullscreen mode

When you need to read the value of WeakRefs, need to use the deref() method to return the instance.

Continuing from the above example,

const copyObj = refObj.deref();
copyObj.name; // Ren
Enter fullscreen mode Exit fullscreen mode

Garbage collectors are complicated. If an application or library depends on GC cleaning up a WeakRef or calling a finalizer in a timely, predictable manner, it's likely to be disappointed: the cleanup may happen much later than expected, or not at all. Sources of variability include:

One object might be garbage-collected much sooner than another object, even if they become unreachable at the same time, e.g., due to generational collection.
Garbage collection work can be split up over time using incremental and concurrent techniques.
Various runtime heuristics can be used to balance memory usage, responsiveness.
The JavaScript engine may hold references to things which look like they are unreachable (e.g., in closures, or inline caches).
Different JavaScript engines may do these things differently, or the same engine may change its algorithms across versions.
Complex factors may lead to objects being held alive for unexpected amounts of time, such as use with certain APIs.

For that reason, using WeakRef is not recommended and it’s best to avoid implementing one if possible unless you really wanna have a bad time (joke).


4. Tuples? Are we Pee-thon ready yet? Nah it's just Typescript lol...

A tuple is a typed array with a pre-defined length and types for each index.

Tuples are great because they allow each element in the array to be a known type of value.

If we want to define a tuple, we specify the type of each element in the array:

//define a tuple
let tup = [number, boolean, string];
// now initialize it!
tup = [5, false, 'Ree Was Here (not Ren btw!)'];
Enter fullscreen mode Exit fullscreen mode

If we happen to have those elements in a wrong order, we get an error.

Check out Read Only Tuple BTW:

// define our readonly tuple
const tup: readonly [number, boolean, string] = [5, true, 'Ree!'];
// throws error as it is readonly.
tup.push('Welp Failure Management');
Enter fullscreen mode Exit fullscreen mode

Guess what? If you were a React Developer, you were using Tuples under the hood 😳


I hope I made you learn something new today! If I did, consider hitting a like, a unicorn and a bookmark on this Post! Also you can hit a star on my current project - Reejs at https://github.com/rovelstars/reejs , a star means a lot to me!

Have a nice day πŸ™ƒ!

Found any Problems with this blog? Comment it down Below!

Top comments (1)

Collapse
 
kiliman profile image
Kiliman

For dynamic imports, this should also work:

let { default: x } = await import("y");
console.log(x());
Enter fullscreen mode Exit fullscreen mode

🌚 Life is too short to browse without dark mode