Understanding ES6 Modules

Understanding ES6 Modules

This ES6 tutorial explores ES6 modules, showing how they can be used today with the help of a transpiler. Understanding ES6 Modules. Code can be split into smaller files of self-contained functionality. The same modules can be shared across any number of applications. Ideally, modules need never be examined by another developer, because they've has been proven to work.

Almost every language has a concept of modules — a way to include functionality declared in one file within another. Typically, a developer creates an encapsulated library of code responsible for handling related tasks. That library can be referenced by applications or other modules.

The benefits:

  1. Code can be split into smaller files of self-contained functionality.
  2. The same modules can be shared across any number of applications.
  3. Ideally, modules need never be examined by another developer, because they’ve has been proven to work.
  4. Code referencing a module understands it’s a dependency. If the module file is changed or moved, the problem is immediately obvious.
  5. Module code (usually) helps eradicate naming conflicts. Function x() in module1 cannot clash with function x() in module2. Options such as namespacing are employed so calls become module1.x() and module2.x().
Where are Modules in JavaScript?

Anyone starting web development a few years ago would have been shocked to discover there was no concept of modules in JavaScript. It was impossible to directly reference or include one JavaScript file in another. Developers therefore resorted to alternative options.

Multiple HTML <script> Tags

HTML can load any number JavaScript files using multiple <script> tags:

<script src="lib1.js"></script>
<script src="lib2.js"></script>
<script src="core.js"></script>
<script>
console.log('inline code');
</script>

The average web page in 2018 uses 25 separate scripts, yet it’s not a practical solution:

  • Each script initiates a new HTTP request, which affects page performance. HTTP/2 alleviates the issue to some extent, but it doesn’t help scripts referenced on other domains such as a CDN.
  • Every script halts further processing while it’s run.
  • Dependency management is a manual process. In the code above, if lib1.js referenced code in lib2.js, the code would fail because it had not been loaded. That could break further JavaScript processing.
  • Functions can override others unless appropriate module patterns are used. Early JavaScript libraries were notorious for using global function names or overriding native methods.

Script Concatenation

One solution to problems of multiple <script> tags is to concatenate all JavaScript files into a single, large file. This solves some performance and dependency management issues, but it could incur a manual build and testing step.

Module Loaders

Systems such as RequireJS and SystemJS provide a library for loading and namespacing other JavaScript libraries at runtime. Modules are loaded using Ajax methods when required. The systems help, but could become complicated for larger code bases or sites adding standard <script> tags into the mix.

Module Bundlers, Preprocessors and Transpilers

Bundlers introduce a compile step so JavaScript code is generated at build time. Code is processed to include dependencies and produce a single ES5 cross-browser compatible concatenated file. Popular options include Babel, Browserify, webpack and more general task runners such as Grunt and Gulp.

A JavaScript build process requires some effort, but there are benefits:

  • Processing is automated so there’s less chance of human error.
  • Further processing can lint code, remove debugging commands, minify the resulting file, etc.
  • Transpiling allows you to use alternative syntaxes such as TypeScript or CoffeeScript.
ES6 Modules

The options above introduced a variety of competing module definition formats. Widely-adopted syntaxes included:

  • CommonJS — the module.exports and require syntax used in Node.js
  • Asynchronous Module Definition (AMD)
  • Universal Module Definition (UMD).

A single, native module standard was therefore proposed in ES6 (ES2015).

Everything inside an ES6 module is private by default, and runs in strict mode (there’s no need for 'use strict'). Public variables, functions and classes are exposed using export. For example:

// lib.js
export const PI = 3.1415926;

export function sum(...args) {
  log('sum', args);
  return args.reduce((num, tot) => tot + num);
}

export function mult(...args) {
  log('mult', args);
  return args.reduce((num, tot) => tot * num);
}

// private function
function log(...msg) {
  console.log(...msg);
}

Alternatively, a single export statement can be used. For example:

// lib.js
const PI = 3.1415926;

function sum(...args) {
  log('sum', args);
  return args.reduce((num, tot) => tot + num);
}

function mult(...args) {
  log('mult', args);
  return args.reduce((num, tot) => tot * num);
}

// private function
function log(...msg) {
  console.log(...msg);
}

export { PI, sum, mult };

import is then used to pull items from a module into another script or module:

// main.js
import { sum } from './lib.js';

console.log( sum(1,2,3,4) ); // 10

In this case, lib.js is in the same folder as main.js. Absolute file references (starting with /), relative file references (starting ./ or ../) or full URLs can be used.

Multiple items can be imported at one time:

import { sum, mult } from './lib.js';

console.log( sum(1,2,3,4) );  // 10
console.log( mult(1,2,3,4) ); // 24

and imports can be aliased to resolve naming collisions:

import { sum as addAll, mult as multiplyAll } from './lib.js';

console.log( addAll(1,2,3,4) );      // 10
console.log( multiplyAll(1,2,3,4) ); // 24

Finally, all public items can be imported by providing a namespace:

import * as lib from './lib.js';

console.log( lib.PI );            // 3.1415926
console.log( lib.add(1,2,3,4) );  // 10
console.log( lib.mult(1,2,3,4) ); // 24

Using ES6 Modules in Browsers

At the time of writing, ES6 modules are supported in Chromium-based browsers (v63+), Safari 11+, and Edge 16+. Firefox support will arrive in version 60 (it’s behind an about:config flag in v58+).

Scripts which use modules must be loaded by setting a type="module" attribute in the <script> tag. For example:

<script type="module" src="./main.js"></script>

or inline:

<script type="module">
  import { something } from './somewhere.js';
  // ...
</script>

Modules are parsed once, regardless of how many times they’re referenced in the page or other modules.

Server Considerations

Modules must be served with the MIME type application/javascript. Most servers will do this automatically, but be wary of dynamically generated scripts or .mjs files (see the Node.js section below).

Regular <script> tags can fetch scripts on other domains but modules are fetched using cross-origin resource sharing (CORS). Modules on different domains must therefore set an appropriate HTTP header, such as Access-Control-Allow-Origin: *.

Finally, modules won’t send cookies or other header credentials unless a crossorigin="use-credentials" attribute is added to the <script> tag and the response contains the header Access-Control-Allow-Credentials: true.

Module Execution is Deferred

The <script defer> attribute delays script execution until the document has loaded and parsed. Modules — including inline scripts — defer by default. Example:

<!-- runs SECOND -->
<script type="module">
  // do something...
</script>

<!-- runs THIRD -->
<script defer src="c.js"></script>

<!-- runs FIRST -->
<script src="a.js"></script>

<!-- runs FOURTH -->
<script type="module" src="b.js"></script>

Module Fallbacks

Browsers without module support won’t run type="module" scripts. A fallback script can be provided with a nomodule attribute which module-compatible browsers ignore. For example:

<script type="module" src="runs-if-module-supported.js"></script>
<script nomodule src="runs-if-module-not-supported.js"></script>

Should You Use Modules in the Browser?

Browser support is growing, but it’s possibly a little premature to switch to ES6 modules. For the moment, it’s probably better to use a module bundler to create a script that works everywhere.

Using ES6 Modules in Node.js

When Node.js was released in 2009, it would have been inconceivable for any runtime not to provide modules. CommonJS was adopted, which meant the Node package manager, npm, could be developed. Usage grew exponentially from that point.

A CommonJS module can be coded in a similar way to an ES2015 module. module.exports is used rather than export:

// lib.js
const PI = 3.1415926;

function sum(...args) {
  log('sum', args);
  return args.reduce((num, tot) => tot + num);
}

function mult(...args) {
  log('mult', args);
  return args.reduce((num, tot) => tot * num);
}

// private function
function log(...msg) {
  console.log(...msg);
}

module.exports = { PI, sum, mult };

require (rather than import) is used to pull this module into another script or module:

const { sum, mult } = require('./lib.js');

console.log( sum(1,2,3,4) );  // 10
console.log( mult(1,2,3,4) ); // 24

require can also import all items:

const lib = require('./lib.js');

console.log( lib.PI );            // 3.1415926
console.log( lib.add(1,2,3,4) );  // 10
console.log( lib.mult(1,2,3,4) ); // 24

So ES6 modules were easy to implement in Node.js, right? Er, no.

ES6 modules are behind a flag in Node.js 9.8.0+ and will not be fully implemented until at least version 10. While CommonJS and ES6 modules share similar syntax, they work in fundamentally different ways:

  • ES6 modules are pre-parsed in order to resolve further imports before code is executed.
  • CommonJS modules load dependencies on demand while executing the code.

It would make no difference in the example above, but consider the following ES2015 module code:

// ES2015 modules

// ---------------------------------
// one.js
console.log('running one.js');
import { hello } from './two.js';
console.log(hello);

// ---------------------------------
// two.js
console.log('running two.js');
export const hello = 'Hello from two.js';

The output for ES2015:

running two.js
running one.js
hello from two.js

Similar code written using CommonJS:

// CommonJS modules

// ---------------------------------
// one.js
console.log('running one.js');
const hello = require('./two.js');
console.log(hello);

// ---------------------------------
// two.js
console.log('running two.js');
module.exports = 'Hello from two.js';

The output for CommonJS:

running one.js
running two.js
hello from two.js

Execution order could be critical in some applications, and what would happen if ES2015 and CommonJS modules were mixed in the same file? To resolve this problem, Node.js will only permit ES6 modules in files with the extension .mjs. Files with a .js extension will default to CommonJS. It’s a simple option which removes much of the complexity and should aid code editors and linters.

Should You Use ES6 Modules in Node.js?

ES6 modules are only practical from Node.js v10 onwards (released in April 2018). Converting an existing project is unlikely to result in any benefit, and would render an application incompatible with earlier versions of Node.js.

For new projects, ES6 modules provide an alternative to CommonJS. The syntax is identical to client-side coding, and may offer an easier route to isomorphic JavaScript, which can run in the either the browser or on a server.

Module Melee

A standardized JavaScript module system took many years to arrive, and even longer to implement, but the problems have been rectified. All mainstream browsers and Node.js from mid 2018 support ES6 modules, although a switch-over lag should be expected while everyone upgrades.

Learn ES6 modules today to benefit your JavaScript development tomorrow.

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

What’s new in HTML6

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

JavaScript ES6 Classes

JavaScript ES6 Classes

An exciting new construct that was introduced in the ES6 specification is the ES6 classes. If you're a Javascript developer, you will be aware that Javascript follows prototypal inheritance and sometimes it can get a little messy. However, with ES6 classes the syntax is simpler and much more intuitive.

An exciting new construct that was introduced in the ES6 specification is the ES6 classes. If you're a Javascript developer, you will be aware that Javascript follows prototypal inheritance and sometimes it can get a little messy. However, with ES6 classes the syntax is simpler and much more intuitive.

Classes are a fundamental part of object oriented programming (OOP). They define “blueprints” for real-world object modeling and organize code into logical, reusable parts. Classes share many similarities with regular objects. They have their own constructor functions, properties, and methods. In this tutorial, we’ll demonstrate how to create and work with ES6 classes.

Creating a class

You can create a class using the class keyword:

class Person{

  constructor(name, age) {

    this.name = name

    this.age = age

  }

}



let person = new Person("Sam", 30)



person.name

//returns 'Sam'



person.age

//returns 30

Notice how we define our Person class with a constructor() function taking two arguments name and age. Using the this keyword, we set the name and age properties based on the provided arguments. Remember that the constructor function is called whenever we create a new instance of the Person class.

Similar to objects, we can read class properties using dot notation so that person.name returns Sam.

Defining properties and methods

You can define properties and methods for a class the same way you do for regular objects:

class Person{

  constructor(name, age) {

    this.name = name

    this.age = age

  }



  sayName() {

    console.log("My name is " + this.name)

  }

}



let person = new Person('Tim', 40)



person.sayName()

//logs 'My name is Tim'



person.location = 'London'



person.location

//returns 'London'

Notice how we define a sayName() function within our Person class definition. Once we create a new instance of Person, we can call the method via person.sayName().

You can also add properties and methods on the fly. You’ll notice that while the location property isn’t defined in our constructor function, we can still dynamically add it later on for the person instance. Remember that if we created a new instance of Person, it would not have a location property because that property is not defined in the class definition. Only properties and methods that we explicitly define will be shared by all instances of the class.

Static functions

You can use the static keyword to make class methods static. A static method acts on the class itself, not on instances of the class:

class Person{

  constructor(name, age) {

    this.name = name

    this.age = age

  }



  static describe(){

    console.log("This is a person.")

  }



  sayName() {

    console.log("My name is " + this.name)

  }

}



Person.describe()

//logs 'This is a person.'

Notice how static methods operate on the class itself and not an instance of the class. We didn’t have to create a new Person to call the static method.

Static methods are useful for common or shared class functionality. In this case, the describe() method is used to describe what the Person class is. It will apply to every instance of Person. This is why we make it a static method.

Class Inheritance

Inheritance allows you to create new classes based off existing ones. These new classes “inherit” the methods and properties of their parent. They can also override or extend the parent:

class Person{

  constructor(name, age) {

    this.name = name

    this.age = age

  }


  static describe(){

    console.log("This is a person.")

  }


  sayName() {

    console.log("My name is " + this.name)

  }

}



class Programmer extends Person {

  sayName(){

    console.log("My name is " + this.name + " and I am a programmer!")

  }

}



let averageJoe = new Person('Todd', 40)

let programmer = new Programmer('Sam', 33)



averageJoe.sayName()


//logs 'My name is Todd'


programmer.sayName()


//logs 'My name is Sam and I am a programmer!'

Using the extends keyword, we can create a new class sharing the same characteristics as Person. Notice how we override the sayName() method with a new definition for the Programmer class. Apart from overriding this method, everything else remains the same for both Person and Programmer.

Using super

The super keyword allows a child class to invoke parent class properties and methods.

class Person{

  constructor(name, age) {

    this.name = name

    this.age = age

  }



  static describe(){

    console.log("This is a person.")

  }



  sayName() {

    console.log("My name is " + this.name)

  }

}





class Programmer extends Person {

  sayName(){

    super.sayName()

    console.log("My name is " + this.name + " and I am a programmer!")

  }

}



let averageJoe = new Person('Todd', 40)

let programmer = new Programmer('Sam', 33)



programmer.sayName()



//logs 'My name is Sam'

//logs 'My name is Sam and I am a programmer!'

Notice how we call super.sayName() in the Programmer implementation of sayName(). While this invokes the parent implementation of super.sayName(), the name property still references the Programmer class.

Conclusion

Classes facilitate object oriented programming in JavaScript. While regular objects provide similar functionality, classes provide the extra advantage of inheritance and static methods.

Javascript ES6: Map-Reduce-Filter-Find

Javascript ES6: Map-Reduce-Filter-Find

If you are a fan of javascript and use it daily then you will love this. Way you write your JavaScript by using .map(), .reduce() and .filter() ... concise with arrow functions

If you are a fan of javascript and use it daily then you will love this

Javascript is a language that give freedom of writing code in any style, from imperative to declarative styles. Most programmer use imperative because either they are coming from OOPs background, may be they love it or they are not familiar with other style. Before we dive into the declarative style which is FP, let’s understand the differences in two by looking at an example(If you already know the difference then you may skip few paragraphs).

Imperative

// to calculate the sum of array elements
const sum = (arr) => {
  let result = 0; 
  for (let i = 0; i < arr.length; i++) {
    result += arr[i];
  }  
  return result;
};

Imperative style is cool but imagine what if there is a complex mathematics logic here then size of code and the readability will suck. It increases the cognitive load when reading, and over time makes it easier to faulter in reasoning and logic. Also, the main complexity of this code snippet derives from the fact that instead of telling the computer what we want it to do, we are instructing it on how to do it.

Declarative

// calculate the sum of array elements
const sum = (arr) => arr.reduce((total, item) => total += item, 0);

Now, this looks pretty clean, shorter, expressive, concise code, less error prone, easier to maintain and easier to debug. We are telling computer what we want it to do rather how to do it.

Declarative approach are easily optimisable at complier end and also have less side effects.

Note: if you are concerned about the performance of above two and other javascript function (map, reduce, filter, find) then you should for small data set and can view here for large data set(100–1000000)

Without more delay, let’s start the real action with most used Javascript function for functional programming.

Map

// definition 
collection.map((currentValue, index) => {
    // Return element for newArray
});
// example
const arr = [1,2,3,4,5];
const newArray = arr.map(i => i*10);
// return a new array with all value as multiple of 10;

Map works on an array and return an array that’s it. Above code snippet works on an collection i.e an array and takes a callback with current iteration value, index as arguments and return a new array.

Note: Maps are well suited for change/transforming whole array rather than breaking the flow for some conditions, Map suck’s performance wise, check out "underlined" here but are easy to be used for small data sets.

Reduce

// definition 
collection.reduce((accumulator, item, index) => {
    // logic to perform to get accumulator as a return value
}, initialValue for accumulator);
// example
const arr = [1,2,3,4,5];
const total = arr.reduce((acc, item) => acc+= item, 0);
// return a total as 15

Reduce works on an array but can return anything you want it to return. As the name speaks for itself it can be reduce to anything and can behave like map, find, filter or any other javascript function. The above code snippet works on an array and reduce to compute the total value of item of array.

Explanation of example above : On reduce first run, acc is assigned a 0 value and then acc+= item i.e acc = acc+item which will compute to0+1 i.e 1. This 1 will be acc value for next iteration and this continues until we are done with all array items.

Find

// definition 
collection.find((item) => {
    // return first element that satisfy the condition
});
// example
const arr = [1,2,8,4,5];
const value = arr.find(i => i%4 == 0);
// return the first value i.e 8 

Find works on an array and return the first element that satisfy the condition in function.

Note: Easy, simple but not efficient on large data set, why ? look here

Filter

// definition 
collection.filter((currentValue, index) => {
    // logic to filter array on
});
// example
const arr = [1,2,3,4,5];
const newArray = arr.filter(i => i%2 == 0);
// return a new array with value [2, 4]

Filter works on array return an array for filtered items.


Lets use them for some real world scenarios + some ES6. (lets try some ARMD on below object keys)

Wondering what is ARMD its Add, Read, Modify, Delete, its cool to coin your own jargon

const users = [
  {
    id: 1,
    name: "Jonathon Haley",
    username: "Monte.Weber2",
    email: "[email protected]",
    phone: "1-563-675-1857 x11708",
    website: "carmela.net",
    password: "hashed_password"
  },
  {
    id: 2,
    name: "Dean John",
    username: "dd.1",
    email: "[email protected]",
    phone: "1-123-543-1857 123212",
    website: "dd.net",
    password: "Dean_hashed_password"
  }

We will use users as array for further examples

1. ARMD — Adding a new element to users

const newUser = {
    id: 4,
    name: "Denomer Crazy",
    username: "crazy.1",
    email: "[email protected]",
    phone: "",
    website: "crazy.app",
    password: "crazed_checker"
};
const newData = [...users, newUser]; // add element at last
or 
const newData = [newUser, ...users]; // add element at first
or 
const newData = users.concat(newUser) // the old way

The use of es6 spread operator make super easy to add elements to array. We can use spread operator to concat two different array, modify shape of objects or add dynamic key value pairs etc.

const hobbies = ['chess', 'pool'];
const newUsers = users.map(u => ({...u, hobbies}))
// this will add hobbies to users array and return newUsers array

2. ARMD — Get email address, phone number and website of users into new array

const contactInfo = users.map(({email, website, phone}) => ({email, website, phone}));

The use es6 of destructuring of object keys and map to get the contact info array for user.

3. ARMD — Find and replace value for key of objects

const newUsers = users.map(u => u.id == 2? ({...u, name: 'te'}): u);
// this will return newUsers with all user having name 'te'

4. ARMD —Delete some key’s from object

Note: We will actually not delete the key but return a new object, if you want to delete the key use delete operator, here we are considering object immutability.

To delete keys there are lot of ways but we will look at the most easy, single lined. Lets try to delete website from users.

const newUsers = users.map({id, email, name, username, phone, password} => ({id, email, username, email, phone, password}));
// will return an array with all keys other than website

Above code seems to be practically difficult to code for big objects.

const newUsers = users.map(u => Object.keys(u).reduce((newObj, key) => key != 'website' ? { ...newObj, [key]: u[key]} : newObj, {}));

We map through the users and then on each user we do a reduce and form a new object (newObj) and then check for website key, if its a website we return the previously formed newObj, if not then we do a spread operator and add require key to obj and finally return newObj.

If anything is not clear or you want to point out something, please comment down below.

Thank you

JavaScript Tutorial: if-else Statement in JavaScript

JavaScript Tutorial: if-else Statement in JavaScript

This JavaScript tutorial is a step by step guide on JavaScript If Else Statements. Learn how to use If Else in javascript and also JavaScript If Else Statements. if-else Statement in JavaScript. JavaScript's conditional statements: if; if-else; nested-if; if-else-if. These statements allow you to control the flow of your program's execution based upon conditions known only during run time.

Decision Making in programming is similar to decision making in real life. In programming also we face some situations where we want a certain block of code to be executed when some condition is fulfilled.
A programming language uses control statements to control the flow of execution of the program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program.

JavaScript’s conditional statements:

  • if
  • if-else
  • nested-if
  • if-else-if

These statements allow you to control the flow of your program’s execution based upon conditions known only during run time.

  • if: if statement is the most simple decision making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.
    Syntax:
if(condition) 
{
   // Statements to execute if
   // condition is true
}

Here, condition after evaluation will be either true or false. if statement accepts boolean values – if the value is true then it will execute the block of statements under it.
If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by default if statement will consider the immediate one statement to be inside its block. For example,

if(condition)
   statement1;
   statement2;

// Here if the condition is true, if block 
// will consider only statement1 to be inside 
// its block.

Flow chart:

Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate If statement 

var i = 10; 

if (i > 15) 
document.write("10 is less than 15"); 

// This statement will be executed 
// as if considers one statement by default 
document.write("I am Not in if"); 

< /script> 

Output:

I am Not in if
  • if-else: The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the else statement. We can use the else statement with if statement to execute a block of code when the condition is false.
    Syntax:
if (condition)
{
    // Executes this block if
    // condition is true
}
else
{
    // Executes this block if
    // condition is false
}


Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate If-else statement 

var i = 10; 

if (i < 15) 
document.write("10 is less than 15"); 
else
document.write("I am Not in if"); 

< /script> 

Output:

i is smaller than 15
  • nested-if A nested if is an if statement that is the target of another if or else. Nested if statements means an if statement inside an if statement. Yes, JavaScript allows us to nest if statements within if statements. i.e, we can place an if statement inside another if statement.
    Syntax:
if (condition1) 
{
   // Executes when condition1 is true
   if (condition2) 
   {
      // Executes when condition2 is true
   }
}

Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate nested-if statement 

var i = 10; 

if (i == 10) { 

// First if statement 
if (i < 15) 
	document.write("i is smaller than 15"); 

// Nested - if statement 
// Will only be executed if statement above 
// it is true 
if (i < 12) 
	document.write("i is smaller than 12 too"); 
else
	document.write("i is greater than 15"); 
} 
< /script> 

Output:

i is smaller than 15
i is smaller than 12 too
  • if-else-if ladder Here, a user can decide among multiple options.The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
if (condition)
    statement;
else if (condition)
    statement;
.
.
else
    statement;


Example:

<script type = "text/javaScript"> 
// JavaScript program to illustrate nested-if statement 

var i = 20; 

if (i == 10) 
document.wrte("i is 10"); 
else if (i == 15) 
document.wrte("i is 15"); 
else if (i == 20) 
document.wrte("i is 20"); 
else
document.wrte("i is not present"); 
< /script> 

Output:

i is 20