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.