ES6, ES7, ES8 & Writing Fashionable JavaScript Pt5 – WeakMap, WeakSet and Export & Import




ES6 introduced a variety of new options to JavaScript. On this half, you’ll be taught, perceive and grasp WeakMap, WeakSet and export and import statements, together with dynamic imports. Additionally, you will be taught a bit about weak and robust reference. Be taught the nuts and bolts of ES6 and grow to be a greater JavaScript developer!

ES6, ES7, ES8 & Writing Fashionable JavaScript Part 1 (Scope, let, const, var).

ES6, ES7, ES8 & Writing Fashionable JavaScript Part 2 (Template literals, Destructuring & Default Params).

ES6, ES7, ES8 & Writing Fashionable JavaScript Part 3 (Unfold, Relaxation, Units & Object Literal).

ES6, ES7, ES8 & Writing Fashionable JavaScript Part 4 (Contains, Pads, Loops & Maps).

ES6, ES7, ES8 & Writing Fashionable JavaScript Part 6 (Arrow capabilities & Guarantees).

ES6, ES7, ES8 & Writing Fashionable JavaScript Part 7 (Async/await & Courses).

WeakMap and WeakSet

Within the third half, you’ve realized about Sets. Then, within the fourth half, you’ve additionally realized about Maps. Because the launch of ES6, each these objects even have their “weaker” counterparts. These counterparts are referred to as WeakMap and WeakSet. This raises a query. What’s the distinction between Map and WeakMap and Set and WeakSet?

On this scenario, the phrase “weak” is used to specify a kind of reference, or a kind of pointer. In case of WeakMap it implies that the important thing/worth pairs contained in the WeakMap are weakly referenced (weak pointers). In case of WeakSet they’re the objects contained in the WeakSet which can be referenced weakly (weak pointers). Nonetheless, what does it imply when one thing is referenced weakly?

A weak reference implies that when one thing is faraway from the reminiscence and all references to that factor are eliminated the factor itself may be garbage collected. So, whenever you attempt to entry that factor, you’ll get undefined as a result of there are not any references to it. This isn’t true for issues with sturdy reference. They won’t be rubbish collected if no different reference to it exists.

One other method to put it. A weakly referenced factor (a youthful brother) is protected against rubbish assortment (a bully) solely when another reference to it (an older brother) exists (is shut). When all references are gone (the older brother is elsewhere) the weakly referenced factor (the youthful brother) is not shielded from rubbish assortment (the bully) and it will get collected (will get bullied).

WeakMap

Let’s display this on one easy instance. Within the instance under you initialize two variables, mapExample and weakMapExample, utilizing Map and WeakMap. After that, you add one other variable objExample and initialize it as object with some key and worth. Then, you utilize the objExample so as to add new pair into mapExample and weakMapExample.

Subsequent is a fast examine to see that you would be able to entry this pair, or fairly the worth half, in mapExample in addition to weakMapExample. Following this examine, you set the objExample to null so rubbish assortment can take away it from reminiscence. Lastly, you’ll once more do a fast examine to see if you happen to can nonetheless entry the worth half.

As you’ll be able to see, accessing the worth utilizing get() it appropriately returns undefined for each, the Map (mapExample) in addition to the WeakMap (weakMapExample). Nonetheless, what if you happen to attempt to iterate over the Map (mapExample) utilizing for...of loop? You’ll nonetheless get the worth and even the objExample object even after rubbish assortment did its job!

///
// Map and WeakMap instance:
// Create new Map and WeakMap.
let mapExample = new Map()
let weakMapExample = new WeakMap()

// Create the objExample.
let objExample = {age: 'foo'}

// Output the content material of objExample
console.log(objExample)
// [object Object] {
//   age: 'foo'
// }

// Add the objExample to Map and WeakMap
mapExample.set(objExample, 'foo')
weakMapExample.set(objExample, 'foo')

// Output the content material of map and weakMap
for (let [key, value] of mapExample) {
  console.log(key)
  console.log(worth)
}
// Outputs:
// [object Object] {
//   age: 'foo'
// }
// 'foo'

// Output the content material of Map
console.log(mapExample.get(objExample))
// Outputs: 'foo'

// Output the content material of WeakMap
console.log(weakMapExample.get(objExample))
// Outputs: 'foo'

// Set the objExample to null so rubbish assortment can take away it from reminiscence.
objExample = null

// Output the content material of objExample
console.log(objExample)
// Outputs: null

// !
// PAY ATTENTION HERE!
// The map nonetheless comprises the, now eliminated, objExample!
// Output the content material of Map
for (let [key, value] of mapExample) {
  console.log(key)
  console.log(worth)
}
// Outputs:
// [object Object] {
//   age: 'foo'
// }
// 'foo'

// Output the content material of Map
console.log(mapExample.get(objExample))
// Outputs: undefined

// Output the content material of WeakMap
console.log(weakMapExample.get(objExample))
// Outputs: undefined

WeakSet

Now, let’s take the instance with Map and WeakMap and rewrite it utilizing Set and WeakSet. What if you happen to attempt to examine if the article exists contained in the Set (setExample) and WeakSet (weakSetExample), utilizing has()? Earlier than the elimination, you’ll get true. Each, the Set (setExample) and WeakSet (weakSetExample) include the article. Whenever you attempt to iterate over the Set (setExample) utilizing forEach, you’ll get the article and its content material.

What is going to occur after the elimination? Nicely, you’ll once more appropriately get false for the Set (setExample) in addition to the WeakSet (weakSetExample). Nonetheless, you strive the forEach loop once more you’ll once more get the article and its content material, though the article itself not exists.

///
// Set and WeakSet instance:
// Create new Set and WeakSet
let setExample = new Set()
let weakSetExample = new WeakSet()

let objExample = {identify: 'bar'}

// Output the content material of objExample
console.log(objExample)
// [object Object] {
//   identify: 'bar'
// }

// Add the objExample to Set and WeakSet
setExample.add(objExample)
weakSetExample.add(objExample)

// Output the content material of Set and weakSet
setExample.forEach(merchandise => console.log(merchandise))
// Outputs:
// [object Object] {
//   identify: 'bar
// }

// Output the content material of Set
console.log(setExample.has(objExample))
// Outputs: true

// Output the content material of WeakSet
console.log(weakSetExample.has(objExample))
// Outputs: true

// Set the objExample to null so rubbish assortment can take away it from reminiscence.
objExample = null

// Output the content material of objExample
console.log(objExample)
// Outputs: null

// !
// PAY ATTENTION HERE!
// Output the content material of Set
setExample.forEach(merchandise => console.log(merchandise))
// Outputs:
// [object Object] {
//   identify: 'bar'
// }

// Output the content material of Set
console.log(setExample.has(objExample))
// Outputs: false

// Output the content material of WeakSet
console.log(weakSetExample.has(objExample))
// Outputs: false

The variations between Map & WeakMap and Set & WeakSet

The Map, WeakMap, Set and WeakSet are attention-grabbing options of ES6. Apart to the names and the way they deal with rubbish assortment, there are different variations between these options. Map and WeakMap and Set and WeakSet are very related of their variations. First, WeakMap and WeakSet keys can’t be primitive varieties (string, quantity, boolean, null, undefined, image). WeakMap and WeakSet can retailer solely objects.

Second, WeakMap and WeakSet keys can also’t be created by an array or one other set. Third, WeakMap and WeakSet don’t present any strategies or capabilities that will will let you work with the entire set of keys. Which means, there is no such thing as a measurement or size property and no keys(), values(), entries(), forEach() or for...of.

That is additionally why within the instance above you noticed forEach used solely with Set, not with WeakSet and for...of solely with Map however not with WeakMap. Fourth, WeakMap and WeakSet should not iterable.

Export, import and modules

The export and import statements are in all probability one of the crucial used ES6 options amongst JavaScript developers. What these statements do is that they will let you break up your code into modules you’ll be able to then export and import everytime you need or want. In consequence, will probably be a lot simpler so that you can maintain your code away from redundant repetitions.

The import assertion

Earlier than you get your palms on these ES6 options there’s something it’s worthwhile to know. You possibly can’t use import assertion in embedded scripts by default. If you wish to achieve this, it’s worthwhile to set its kind attribute to “module”. One other attention-grabbing factor on the import is that you would be able to change the identify of the imported export, or a number of, whenever you import it.

You are able to do so utilizing as(import foo as bar from 'module'). You may as well import all exports, or code, from a module utilizing *. Whenever you wish to import one some exports from the module, you are able to do so by separating these exports with comma and wrapping them with curly braces (import { exportOne, exportTwo } from 'module').

Whenever you export one thing concentrate, and keep in mind, to the way you export it. Which means, keep in mind whether or not you exported that factor as a default export or not (or as “named”). This determines the import syntax you will want to make use of to import that export. In the event you export one thing as default export you don’t use curly braces (import defaulExport from 'module').

In the event you export one thing as “named” export, it’s important to use curly braces (import { namedExport } from 'module'). Two final issues about utilizing import assertion it’s worthwhile to know and keep in mind. First, don’t wrap the identify of the export, default or named, in quotes. Second, all the time wrap the identify of the module, the file, you’re importing the export from in quotes.

///
// Import instance no.1: Primary syntax and importing named export
import { someNamedExport } from '/exampleModule.js'


///
// Import instance no.2: Importing a number of named exports
import { foo, bar, bazz, gazz } from '/exampleModule.js'


///
// Import instance no.3: Primary syntax and importing default export
import someDefaultExport from '/exampleModule.js'


///
// Import instance no.4: Importing default and named export
import someDefaultExport, { someNamedExport } from '/exampleModule.js'


///
// Import instance no.5: Importing named export and renaming it
import { someBadlyNamedNamedExportThatIsJustImpossibleToRemember as calc }
  from '/exampleModule.js'


///
// Import instance no.6: Importing default export and renaming it
import someBadlyNamedDefaultExportThatIsJustImpossibleToRemember as fuzzy
  from '/exampleModule.js'


///
// Import instance no.7: Importing a number of exports and renaming them
import { foo as bar, bazz as fuzzy, zazz as zizzy } from '/exampleModule.js'

The export assertion

You understand how all you want about import statements. Now, let’s briefly speak in regards to the export. As I discussed above, there are two varieties of exports, “default” and “named”. As you now know, the kind of export determines what syntax you utilize for import. Import with curly braces with “named” export and with out curly braces with “default” export.

The principles about curly braces you realized about within the half about “named” and “default” import statements additionally apply to exports. Whenever you wish to export one thing as “default” you don’t use curly braces. Whenever you wish to export it as “named” export you utilize curly braces.

One other vital factor that distinguishes “default” and “named” is that you would be able to have just one “default” export per module (file). You possibly can’t use “default” export to export a number of issues. This restrict doesn’t apply to “named” exports. You possibly can have as many “named” exports per module (file) as you need. A number of exports have to be separated by commas.

Subsequent, whenever you wish to export a number of issues you are able to do it both individually or all of sudden. One final thing. What are you able to export? Mainly something. You possibly can export variables, capabilities, courses, objects. The one limitation are in all probability primitives. Which means, you’ll be able to’t import issues reminiscent of string, quantity, booleans, and many others. immediately.

If you wish to export some primitive information kind, it’s important to declare it as a variable first. Then, you’ll be able to export that variable. Lastly, you may also rename the factor you wish to export whenever you export it. This works equally to importing. You once more use as (export foo as bar).

///
// Export instance no.1: Default export
const foo = 'Export me'

export default foo

// or
export default const foo = 'Export me'


///
// Export instance no.2: Named export
const foo = 'Export me'

export { foo }

// or
export const foo = 'Export me'


///
// Export instance no.3: A number of particular person exports
export const foo = 13
export const fizz = 'One other export'
export const bazzy = true


///
// Export instance no.4: A number of exports directly
const foo = 13
const fizz = 'One other export'
const bazzy = true

export { foo, fizz, bazzy }


///
// Export instance no.5: Named and default exports
const foo = 'Default export'
const fizz = 'named export'
export foo, { fizz }

// or
export default const foo = 'Default export'

export const fizz = 'named export'

Dynamic imports

The import and export statements launched in ES6 are nice options. Nonetheless, there may be already a small improve within the making. This at the moment exists solely as a stage 3 proposal. You might be able to import modules dynamically, solely and proper on the time whenever you want them. You’ll principally import module on-demand and never by default. This shall be allowed utilizing “dynamic import”, or import().

For instance, you’ll be able to import a module solely when consumer clicks on a selected button or hyperlink. Or, you’ll be able to import complete web page solely when consumer clicks on particular navigation hyperlink. In any other case, the module won’t be loaded by the browser or app. This may also help you considerably cut back the quantity of sources the web page or must load. And, because of this it might probably load a lot quicker.

The most effective factor about dynamic import is that you need to use it anyplace. You should use it in world scope, inside perform and even inside statements reminiscent of if else or loops. The way it works? Dynamic import all the time returns a promise. And, this promise all the time resolves to the module you wish to import.

What’s extra, if you happen to work with asynchronous code, or async capabilities, you may also mix dynamic imports with await operator. You’ll study promise and async/await within the subsequent a part of this collection.

///
// Dynamic import instance no.1:
const button = doc.querySelector('.cta-btn')
const navLinkAbout = doc.querySelector('.link-about')

// Connect eventListener to the button
button.addEventListener(() => {
  // import particular module when it's wanted
  import('/some-module.js').then((module) => {
    // do one thing
  }).catch((error) => console.log(error))
})

// Connect eventListener to the navigation hyperlink
navLinkAbout.addEventListener(() => {
  // import About web page module when consumer clicks on the navigation hyperlink
  import('/pages/page-about.js').then((module) => {
    // Load the web page
  }).catch((error) => console.log(error))
})


///
// Dynamic import instance no.2: Dynamic import and async/await
async perform someCoolModuleLoader() {
  // Load module combining import with await
  let coolModule = await import('/cool-module.js')

  coolModule.greet() // Use greet() perform from coolModule
  coolModule.default() // Use the default export
}

Epilogue: ES6, ES7, ES8 & Writing Fashionable JavaScript Pt5

Congratulations! You’ve simply completed one other a part of ES6, ES7, ES8 & Writing Fashionable JavaScript collection! As we speak, you’ve realized every part you want about options WeakMap, WeakSet and export and import statements. Lastly, you’ve additionally realized about dynamic imports. Now, you can begin utilizing all these thrilling options with absolute confidence.

Within the subsequent half study in all probability essentially the most highly effective and superior ES6 options you could find. This contains options reminiscent of arrow capabilities, courses, guarantees, async/await and mills. So, get able to take your data of JavaScript to the very best stage.

In the event you favored this text, please subscribe so you do not miss any future publish.








If you would like to assist me and this weblog, you’ll be able to grow to be a patron, or you should buy me a espresso 🙂







Abu Sayed is the Best Web, Game, XR and Blockchain Developer in Bangladesh. Don't forget to Checkout his Latest Projects.


Checkout extra Articles on Sayed.CYou

#ES6 #ES7 #ES8 #Writing #Fashionable #JavaScript #Pt5 #WeakMap #WeakSet #Export #Import