Posts Tagged ‘ES6’

Iterators and Generators| ES6 Features

Posted by

ES6 also known as ES2015 is one of the most popular ECMAScript versions. It introduced some of the most awaited features in JavaScript such as classes, promises, and modules.

For a JavaScript developer, optimization is a never-ending process. This is why we need to stay up to date with the current trends and latest features introduced in JavaScript through the different ECMAScript versions.

To make this process easier for you, we have created a complete guide to ES6 features. The guide covers ES6 features from block-scoping to arrow functions and promises.

In this article, we will cover iterators and generators in ES6 along with the coding examples.

Iterators

An iterator is a JavaScript object that defines a sequence and returns a value upon its termination.  The iterable protocol allows us to loop over custom objects and produce a sequence of values.

In more technical terms, iterators use the next() method to implement the iterator protocol. The next() method returns an object with two properties:

  • value: it provides the next yielded value in the sequence.
  • done: it provides a boolean value, true if it’s the last value in the sequence and false otherwise. 

How Does an Iterator Work in JavaScript?

To use an Iterator, as the name suggests, we have to iterate through the iterable object to get its values. It works by calling the next() method repeatedly and returns {done: false}. Once you have iterated through the last value, the next() method will return {done: true}. Any additional yields will simply keep returning {done: true}.

Iterable Values

The most common iterable in JavaScript is an array iterator. Although, it’s not the only iterator. The iterable values in JavaScript are:

  • Arrays (and typed arrays) 
  • Strings
  • Maps
  • Sets 
  • DOM data structure (in progress) 

Iterables vs. Iterators

Two concepts central to the process of the iteration are iterators and iterables.

Iterator: a data structure (or collection of values) that wants to make its elements publicly accessible. 

Iterable: a pointer (or cursor in the database) that is used to traverse through the elements of a data structure. 

Symbol.iterator

ECMA used the Symbol.iterator protocol to make native objects like arrays iterable. Symbols offer names that are unique and cannot clash with other property names. 

Symbol.iterator returns an object called an iterator. This iterator will have a method called next which will return an object with values and done().

For-of Operator

ES6 introduced the for-of loop (an alternative to the for-in loop) that returns values instead of keys.

In the following coding example, we have created an iterator to store the infamous Fibonacci series. In the next line, we define to use the for-of loop to print all the numbers in a Fibonacci sequence until 100.

Generators

Iterators are a pretty useful concept in JavaScript and so it requires concise programming to maintain its internal state. 

That’s where generator functions come in. They provide a powerful alternative to the useful yet complicated iterators. 

Generators allow us to define an iterative algorithm by writing a special kind of function whose execution is continuous. Generators are defined a little differently from regular functions. Generators are defined using the function* syntax (function keyword with an asterisk)

Before ES6 

Functions in JavaScript break their operation when they come across a return statement. 

For Example:

After ES6 

On the other hand, the generator function works a little differently. It returns a special type of iterator called a generator. When a value is consumed by the next() method, the Generator function executes until it comes across the yield keyword

At the yield keyword, the generator will pause and return a value. The (generator) function can be called multiple times (as much as you want) and returns a new value each time. 

This process is terminated with a return statement. A return statement in the generator (when executed) will make the generator end. Simply put, the return statement in generators works the same way as in regular functions.

In the following example, we have multiple mathematical operations performed on myGenerator using next(). 

The output of the generator function is as follows:

Generators and iterators can be quite confusing to new JavaScript coders as the concepts are quite similar. If you’re still confused between the two then just remember that the generator generates a sequence while the iterator traverses through the collection one at a time.

ES6 features have made JavaScript more powerful and optimised. If you don’t already use the new ES6 features like promises and generators in your code yet, then start today!

Happy Coding!

Modules and Promises in ES6

Posted by

JavaScript was first introduced on December 4, 1995, as a scripting language. Considering it was just supposed to make web pages dynamic, it started pretty small. More features were added (and honed) along the way through the ECMAScript versions. 

In this article, we will discuss two ES6 features called promises and modules. These two ES6 features have made programming complex tasks in Javascript more organised and easier. 

Promises 

Promises are a rather advanced topic in JavaScript. To understand promises, first, you need to be familiar with the concept of asynchronous programming in JavaScript. 

Asynchronous JavaScript

JavaScript is a single-threaded programming language, which means that in a JavaScript program, only one thing can happen at a time. That’s not exactly convenient when we are working on complex logic. 

To solve this issue, asynchronous JavaScript comes into play. Using asynchronous concepts such as promises, callbacks, and async/await, you can perform complex tasks that require long waits without blocking the flow of the program. 

What is a Promise in JavaScript? 

A promise in JavaScript is an object that represents the eventual completion (or failure) of an asynchronous operation with its (final) value. 

The ES6 promise constructor takes a function which can take up to two parameters. Callback functions resolve() or reject() to indicate the success or failure of the promise. 

You can declare a standard script as a module by including type=” module” in the <script> element in the HTML document (refer to the example below).

States of Promise

JavaScript promises are in one of the three following states:

  • Pending: initial (first) stage 
  • Fulfilled: operation completed successfully 
  • Rejected: operation failed 

Pending

Initially, a promise is in the stage of pending which means that it is waiting for something to resume its normal program flow. Now a promise is either fulfilled or rejected. 

Fulfilled

A promise is fulfilled if it’s no longer pending. Which means that it has either been resolved or rejected. A promise is fulfilled by calling the resolve() method.

A promise can not be resettled once it has been settled. Calling resolve() or reject() again will have no effect. In a nutshell, a resolved promise is immutable.  

Rejected 

A promise is rejected if the operation fails. A promise is rejected by calling the reject() method.

How to Use Promises in ES6

To help you understand promises, let us consider a scenario where the program will wait for two seconds before sending a message to the user.

In the example above, 

  • The sendMessage call will wait for two seconds before sending the “Hello World” message. 
  • The setTimeout() method will create the delay and call the resolve() method afterward
  • The function only takes the resolve() parameter only 
  • The resolve() parameter value is then passed through the callback function attached with .then(). 

Modules

As we discussed above, the JavaScript programs used to be shorter aimed at making web pages more interactive. In a complex JavaScript program, you can use modules to distribute the code into different parts. Modules organise code and make it easily accessible and readable. 

A module in JavaScript is just a file. If a project contains three JavaScript (.js) files then each file is a distinct module. We can use import/export to exchange functionality between different modules. 

Exporting Values 

The import keyword labels variables and functions in one script that are accessible in another script. 

In the following, we will export a variable and a function from modules/math.js script. 

Importing Values 

The export keyword allows one script to import functionalities from another script.

In the following example, we will import modules/math.js file into the main script. 

Default Export Vs Named Export

In the example above, we have used named exports. Each item (function and variable) is referred to by its name upon export. The same name is used in the other script where it’s imported. 

The default export is another kind of export aimed at making it easier to have a default function provided by a module in JavaScript. 

To export a function as default, we use the keyword export default before the object name. 

For Example:

We can also prepend export default in front of a function and make it an anonymous function. 

For Example:

Notice the lack of curly braces in the examples above. It’s because there is only one default export allowed per module. In the above example, we know that the square is the default module.

Difference Between Standard Scripts and Modules

Modules are scripts but there are a few important differences between modules and scripts to keep in mind. 

  • Modules might behave differently as compared to the standard scripts. It’s because modules automatically execute in strict mode.
  • Developers often face CORS errors during local testing due to JavaScript code security requirements. The alternate (and best course) is to use a server for testing.
  • Modules are deferred automatically.
  • Modules are executed only once in a script
  • Module features are imported into the scope of a single script. You cannot access module features in the global scope.

Modules are a comparatively new but easy concept to understand. Whereas, promises are a quite complex concept. But both promises and modules have made coding in JavaScript more organised and clean. Make sure that you try both of these interesting ES6 features in your code to add extra and interesting functionality. 

Classes and Object Literals | ES6 Features

Posted by

JavaScript remains one of the most popular programming languages in 2020. JavaScript was initially created to make the web pages more interactive. 

Unlike other programming languages such as Java and C#, JavaScript was perfected over the years through different ECMAScript versions. Each ECMAScript version hones the old features and introduces new features to make JavaScript more powerful and concise. 

In this article, we will discuss two object-oriented programming concepts introduced in ES6, classes, and object literals.

Classes

Classes are one of the most awaited features introduced in ES6. If you have worked with Java or Python, then you will be no stranger to classes. 

A class in JavaScript is a unique function that is created using the keyword ’class’. It’s basically a blueprint for objects in JavaScript. The class body is enclosed in curly brackets and contains properties and methods. 

A significant difference between classes and functions is hoisting. 

Hoisting

Hosting is the default behavior of the JavaScript language where variables and functions declarations are moved to the top. To put it simply, in JavaScript we can access a variable or function before declaring it in the document.

Functions and variables in JavaScript are hoisted while classes are not. Unlike functions, you can not access a class before declaring it first. Doing which will result in a reference error

Note: the code within the class body is always executed in a strict mode. It prevents certain actions from taking place within the class body and throws exceptions.

Class Definition in JavaScript

Classes in JavaScript can be defined in two ways:

  • Class keyword
  • Class expressions

Class Definition using the Class Keyword

Classes in JavaScript can be defined using the class ‘keyword’ along with the name of the class. 

In the example below, we have defined a Person class using the class keyword:

Class Definition using the Class Expressions

Class expressions are another way to define classes in JavaScript. Class expressions can be both named or unnamed. A named class expression is local to the body of the class. It can be retrieved using the name property of the class.

In the example below, we have used the class expressions to define two classes (named and unnamed) and access their name property:

Class Constructors

Class constructors are a special member function of the JavaScript class. The constructor method is used to create and initialize new objects in a class. 

There can be only one constructor function in a class. Adding more than one contractor method will result in a syntax error.

Note: If we don’t use a constructor method, JavaScript will automatically add an (empty and invisible) constructor method in the class body.

Methods and Properties in JavaScript Classes

Classes contain methods and properties. These class members are defined within the body of the class i.e. inside the curly brackets.

  • Methods are actions that the JavaScript objects can perform
  • Properties are characteristics of a JavaScript object

In more technical terms, methods are functions associated with the class and properties are variables associated with the class.

For example:

Enhanced Object Literals

In JavaScript, almost everything is an object. In fact, all JavaScript values are objects except for the primitive values (number, boolean, etc). 

The simplest and fastest way to define objects in JavaScript is through the object literals. To create a JavaScript object using object literal, we simply list the values in ‘key: value’ pairs separated with commas. These values can be functions or properties.

ES6 has introduced a more precise way of declaring object literals. We’ll discuss three major ways introduced in ES6 to make object literals more precise. 

  • Shorthand for initializing properties
  • Shorthand for defining methods
  • Computing property names and expressions

Shorthand for Initializing Properties

Before ES6, initializing object properties was kind of tedious. In the following coding example, we’ll demonstrate how object properties were defines before and after ES6. 

Notice how we no longer need to assign each parameter value to the property. It basically checks if the object property key has a corresponding variable name and assigns the value of the variable to the object property. If no such variable is found, then it simply throws an error.

Shorthand for Defining Methods

Before ES6, a function keyword was used to define functions in objects. Once again, ES6 eliminated the unnecessary keywords and operators to make the code cleaner. 

In the following coding example, we have demonstrated how functions were defined before and after the enhanced object literals.

Computing Property Names and Expressions

Computed expressions are an interesting and innovative enhancement to the object literals in ES6. You must’ve seen something similar in the destructuring assignment topic. 

Basically, there are two ways to specify a key to an object property: dot notation and square brackets notation. The bracket notation enables us to access values using an expression. 

With computed property expressions, we can use square brackets to provide a regular expression instead of a regular property name. The property name is evaluated using a regular expression.

In the following example, we will demonstrate how property names can be computed.

The value of the name was computed to “brand”, which is what we used to access the property value. 

Similarly, in the following example, the value of ‘i’ is evaluated and used as a property name:

Classes and object literals have introduced a very concise and powerful way to code in JavaScript. Whether you’re a new JavaScript developer or experienced, these features will add character to your projects.

Destructuring and Template Strings | ES6

Posted by

JavaScript is one of the most popular programming languages in 2020. What’s unique about javaScript is that it wasn’t released as a complete programming language. JavaScript was improved over the years through ECMAScript versions. 

ES6 also known as ES2015 is one of the most popular ECMAScript versions. It introduced multiple new features and improved some old ones. 

In this article, we will be discussing two ES6 features that have made our code more precise and cleaner:

  • Destructuring assignment
  • Template strings

We’ll discuss each concept with its use cases, the problems it solved, along with the coding examples. So, without further ado, let’s move on!

Destructuring Assignment

Destructuring in JavaScript allows us to extract array elements and object properties and store them in variables. Destructuring is a lot similar to the spread operator that we discussed before but the concept is a little different. 

The spread operator takes all the elements of an array and puts them into another array. 

Destructuring allows users to take single elements from an array or object and store them in a distinct variable. 

Destructuring Assignment and Spread Operator

As destructuring is often confused with the spread operator, we’ll discuss how destructuring assignment and spread operator works first. As we know that the spread operator (…) can be used to unpack and assign values to new variables in an array.

In the following example, we’ve created an array called x and assign its first and second index values to variables a, b, and spread the rest into the variable using the spread (…) operator. 

Array Destructuring 

We can assign the values of array elements to other variables using the destructuring assignment. 

In the following example, we’ve created an array called numbers and assign the first two elements values to variables a and b. 

In array destructuring, the order of the elements defines its values. 

In the next example, we’ve demonstrated the concept of order in destructuring by leaving blank space between commas. The space between the first and last elements indicates that the second element must be ignored while destructuring the array. 

If the variables have a default value then the new value will be reassigned to the variable. 

In the following example, we’ve default values 3 and 5 to variables a and b. Using destructuring, we’ve assigned a = 1 while b = undefined. In this case, the default value of b will be used.

Object Destructuring 

Object destructuring in JavaScript is similar to array destructuring. Although in array destructuring, we assigned values with respect to the order. In object destructuring, we assign values using the property name. 
In the following example, we’ve assigned a value of the 30 to the age variable only (on the left-hand side). When logged on the console, the function only returned a value of 30 for age whereas the name variable returned undefined.

A variable can be assigned a default value if the value undefined is unpacked from the object. 

In the following example, we have an object with two variables a and b with the default values of 30 and 7. The unpacked value for b is undefined. In which case, the default value is used.

Template Literals

Templates literals are an innovative way to present text in JavaScript. Template literals are basic string literals enclosed by backticks (` `) instead of double or single quotes and allow embedded expressions. 

With template literals, we can do the following functions:

  • String and expression interpolation
  • Multi-line strings
  • String tagging 

Templates literal is not an entirely new ES6 feature. Before ES6, it was called template strings but lacked some finer details that were in the later ECMAScript versions.  

Template literals also known as string interpolation is a well-known concept in other programming languages like Perl, Python, and Ruby

String and Expression Interpolation 

Template literals contain placeholders ‘{variable}’ that can be used to insert the value of a variable in a string. A template literal can have more than one placeholder. When the function is called, everything enclosed in (` `) is passed, all the expressions along with the rest of the text.

Multi-line Strings

In string literals, we require an escape sequence (/n) to invoke a newline character. Template literals made it much simpler. In template literals, we can add a new line by pressing the enter key on the keyboard.

Tagged Templates

Tagged templates are a comparatively advanced concept. Tags only work within the confines of the backticks (` `). The tags allow users to combine template literals with custom functions to provide powerful functionality. 

You can choose any name for your tag function (As long as it follows the general rules for setting variable names in JavaScript). 

Tagged templates are used by a number of JavaScript libraries such as Styled Components, and GraphQL

Raw Strings

Tagged templates also include a special raw property. It’s available on the first parameter of the tag function. The raw string can be accessed as it is. 

For example, if you wrote an escape character in the raw string, it will be printed as it was written and not as the character.

Notice how the escape character ‘\n’ was printed instead of starting a new line. 

Template strings and destructuring assignments can be a confusing concept for old JavaScript coders but they can make your code very concise and clean. Apply the concepts in your JavaScript code and you’ll automatically see the difference!