What is a WeakMap in ES6?


A WeakMap is just like a normal Map with a few key differences:

  1. a WeakMap can only contain objects as keys,
  2. a WeakMap is not iterable which means it can’t be looped and
  3. a WeakMap does not have a .clear() method.

Below example shows how to create a WeakMap, it just like you would a normal Map, except that you use the WeakMap constructor.

const book1 = { title: ‘book 1’, author: ‘author 1’ };
const book2 = { title: ‘book 2’, author: ‘author 2’};
const book3 = { title: ‘book 3’, author: ‘author 3’ };

const library = new WeakMap();
library.set(book1, true);
library.set(book2, false);
library.set(book3, true);

console.log(library);

Output:

WeakMap {Object {title: ‘book 1’, author: ‘author 1’ => true, Object {title: ‘book 2’, author: ‘author 2’} => false, Object {title: ‘book 3’, author: ‘author 3’} => true}

…but if you try to add something other than an object as a key, you’ll get an error!

library.set(‘book 4’, false);
Uncaught TypeError: Invalid value used as weak map key(…)

This is because WeakMap can only contain objects as keys. WeakMaps leverage garbage collection for easier use and maintainability.

ES6 Default Function Parameters


Unlike the defining the default values in JavaScript, ES6 has provided a flexibility to define the default values during the function definition time.  In regular Javascript, we define a variable with one value, override that value with in the function logic. Here is an example to define default values in ES6.

function greet(name = ‘Student’, greeting = ‘Welcome’) {
return `${greeting} ${name}!`;
}

greet(); // Welcome Student!
greet(‘Mallik’); // Welcome Mallik!
greet(‘Mallik’, ‘Hi’); // Hi Mallik!

Output of above function:

Welcome Student!
Welcome Mallik!
Hi Mallik!

To create a default parameter, you add an equal sign ( = ) and then whatever you want the parameter to default to if an argument is not provided. In the above example, both parameters have default values of strings, but they can be any JavaScript type!

Arrow Functions in ES6


ES6 introduces a new kind of function called arrow function. Arrow functions are very similar to regular functions in behavior, but are quite different syntactically. They will save developers time and simplify function scope. The following code takes a list of names and converts each one to uppercase using a regular function:

const upperizedNames = [‘Mallik’, ‘Talks’, ‘Java’].map(function(name) {
return name.toUpperCase();
});

The code below does the same thing except instead of passing a regular function to the map() method, it passes an arrow function. Notice the arrow in the arrow function ( => ) in the code below:

const upperizedNames = [‘Mallik’, ‘Talks’, ‘Java’].map(
name => name.toUpperCase()
);

The only change to the code above is the code inside the map() method. It takes a regular function and changes it to use an arrow function.

Another Example for Arrow Functions is below:

var multiply = (x, y) => x*y;

Arrow functions are always function expressions, their full name is “arrow function expressions”, so they can only be used where an expression is valid. This includes being:

  • stored in a variable,
  • passed as an argument to a function,
  • and stored in an object’s property.

If there are zero items in the list, then you need to wrap the list in parentheses:

// empty parameter list requires parentheses
const sayHi = () => console.log(‘Hello MallikTalksJava!’);
sayHi();

If there’s only one parameter in the list, then you can write it just like the example below.

name => `Hello ${name}!`

If there are multiple parameters in the list, then you can write it just like the example below.

const orderIceCream = (flower, color) => console.log(`Color of ${flower} flower is ${color}.`);
orderIceCream(‘Rose’, ‘Red’);

There are two types syntaxes for arrow functions:
1. concise body syntax : All the examples mentioned above are comes under this category.
2. block body syntax : If you need more than just a single line of code in your arrow function’s body, then you can use the “block body syntax”.

const upperizedNames = [‘Mallik’, ‘Talks’, ‘Java’].map( name => {
name = name.toUpperCase();
return `${name} has ${name.length} characters in their name`;
});

Advantages of Arrow functions:

  • The syntax is a lot shorter,
  • it’s easier to write and read short, single-line functions,
  • and they automatically return when using the concise body syntax!

ES6 variable declaration – let and const


In standard Javascript, the only way to declare a variable in JavaScript was to use the keyword var.

But, in ES6 there are now two new ways to declare variables in JavaScript: let and constlet and const have some other interesting properties.

  • Variables declared with let can be reassigned, but can’t be redeclared in the same scope.
  • Variables declared with const must be assigned an initial value, but can’t be redeclared in the same scope, and can’t be reassigned.

Below is the example to show how let and const is being used:

const CHARACTER_LIMIT = 255;
const posts = [
"Mallik",
"talksjava ",
".com"
];

// prints posts to the console
function displayPosts() {
for (let i = 0; i < posts.length; i++) {
console.log(posts[i].slice(0, CHARACTER_LIMIT));
}
}

displayPosts();

Output:

Mallik

talksjava

.com

The big question is when should you use let and const? The general rule of thumb is as follows:

  • use let when you plan to reassign new values to a variable, and
  • use const when you don’t plan on reassigning new values to a variable.

Since const is the strictest way to declare a variable,  you always declare variables with const because it’ll make your code easier to reason about since you know the identifiers won’t change throughout the lifetime of your program. If you find that you need to update a variable or change it, then go back and switch it from const to let.

Example Program to combine arrays in ES6


Here is one example of when the spread operator can be useful is when combining arrays.

If you’ve ever needed to combine multiple arrays, prior to the spread operator, you were forced to use the Array’s concat() method.

const fruits = [“apples”, “bananas”, “pears”];
const vegetables = [“corn”, “potatoes”, “carrots”];

const produce = […fruits, …vegetables];

console.log(produce);

Output :

[ ‘apples’, ‘bananas’, ‘pears’, ‘corn’, ‘potatoes’, ‘carrots’ ]

ES6 Spread Operator


The spread operator, written with three consecutive dots ( … ), is new in ES6 and gives you the ability to expand, or spread, iterable objects into multiple elements.

Example 1: Array Elements Spread

const books = [“Mallik”, “Talks”, “Java”, “.com”];
console.log(…books);

output:

Mallik Talks Java .com

Example 2: Set Elements Spread

const primes = new Set([2, 3, 5, 7, 11, 13, 17, 19, 23, 29]);
console.log(…primes);

Output:

2 3 5 7 11 13 17 19 23 29

If you look at the output from the examples, notice that both the array and set have been expanded into their individual elements. Sets are a new built-in object in javascript in ES6.

ES6 for…of Example Program – Replace first letter of String with Uppercase


Below example iterates days array using for…of operation in ES6 and replaces the first character of the day with upper case.

/*
* Programming Quiz: Writing a For…of Loop (1-4)
*/

const days = [‘sunday’, ‘monday’, ‘tuesday’, ‘wednesday’, ‘thursday’, ‘friday’, ‘saturday’];

for (const day of days ){
console.log(day.charAt(0).toUpperCase() + day.slice(1));
}

Below is the Output of the Program:

Sunday

Monday

Tuesday

Wednesday

Thursday

Friday

Saturday

NgModule Properties in Angular 2


NgModule is a decorator function that takes a single metadata object whose properties describe the module. The most important properties are:

declarations – the view classes that belong to this module. Angular has three kinds of view classes: components, directives, and pipes.
exports – the subset of declarations that should be visible and usable in the component templates of other modules.
imports – other modules whose exported classes are needed by component templates declared in this module.
providers – creators of services that this module contributes to the global collection of services; they become accessible in all parts of the app.
bootstrap – the main application view, called the root component, that hosts all other app views. Only the root module should set this bootstrap property.

Source: https://angular.io/

Components of Angular 2


Below are the major  components of Angular 2

Modules − This is used to break up the application into logical pieces of code. Each piece of code or module is designed to perform a single task.

Component − This can be used to bring the modules together.

Templates − This is used to define the views of an Angular JS application.

Metadata − This can be used to add more data to an Angular JS class.

Service − This is used to create components which can be shared across the entire application.

 

Angular 2 Features


Angular 2 is a opensource javascript framework developed by developers at google. This framework is used to build the single page applications. Angular 2 has been built by considering the difficulties faced in Angular 1 and Angular 2 removes the obstucles in building single page applications.

Blow are the special features of Angular 2:

Components − Angular 2 is a componenent based framework where as Angular 1 is Controller based framework. Components help to build the applications into many modules. This helps in better maintaining the application over a period of time.

TypeScript − Angular 2 is based on TypeScript(a language for application scale JavaScript development). This is a superset of JavaScript that compiles to clean JavaScript output.

Services − Services are a set of code that can be shared by different components of an application. So for example if you had a data component that picked data from a database, you could have it as a shared service that could be used across multiple applications.