/ JavaScript

ES6 - Features - Part I

This post is the first of a series of posts about the ES6 features. If you come from a language like C# you see familiar concepts, I like the ES6 approach to give the developers which use JavaScript more functionality.

Unfortunately, most of the browsers don't cover 100% of the ES6 features, take a look at the ES6 compatibility table. Even though you are using a compiler like Babel, you still only be able to use around 71% of the ES6 features.

Block Scoping

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/block

What is block-scoped? A block is created between { ... }, this can be for example a function or an if statement.

If we declare a variable in curly braces the scope is limited to the braces block. When the block terminates our local variables are also terminated.

let beerId = 10;
{
  let beerId = 42;
}
console.log(beerId);
// result 12
{
  let beerId = 42;
}
console.log(beerId)
// result: refrence error

let

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

What is hoisting? Without let, a variable can be declared after it has been used.

By using let we make sure that the variable declaration takes place before it gets used, no hoisting takes place. In addition, let variables are block-scoped.

Arrow Functions =>

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
With arrow functions, we can omit the function keyword and the return statement. The syntax of an arrow function has zero or more parameters, the arrow => itself and the function statement.

const name = (parameters) => {
    statements
}

Arrow functions have a shorter syntax than normal functions, we just remove the function keyword and replaced it with an arrow =>. Please keep in mind arrow functions don’t bind .this to the object that called them, you cannot bind, applyor call an object to an arrow function.

  • If our arrow function has 0 parameters, we need to use an empty parenthesis.
    () => { statements }
    
  • If our arrow function has 1 parameter, we don't need parenthesis.
    parameter => { statements }
    
  • If our arrow function has 2 or more parameter we have to define the parameter with parenthesis.
    (firstParameter, secondParameter) => { statements }
    

Default Parameters

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters

function(parameter = defaultvalue){ 
  statements 
};

// MDN syntax specification
function [name]([param1[ = defaultValue1 ][, ..., paramN[ = defaultValueN ]]]) {
   statements
};

Default parameters allow us to initialize parameters with a default value if no value or undefined is passed in. The default can be a number, another variable or even a function.

If no argument is passed into the function the parameter default is set to undefined.

var addBeer = function(name, category = 'Pils') {
  console.log(name + ' ' + category);
};

addBeer(); // output: undefined Pils
addBeer('Bitburger'); // output: Bitburger Pils
addBeer('Bolten', 'Alt'); // output: Bolten Alt
var getBeerPrice = function(price, tax = price * 0.09){
  console.log(price + tax);
};

getBeerPrice(5); // output: 5.45

Rest

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters

In ES6 ... indicates the Rest operator, followed by a parameter, it is mainly used to combine an infinite number of arguments to an array by getting all the arguments passed to the function call.

Rest parameter can only be the last parameter. If you don't pass any arguments into the function the numbers parameter is set to an empty array.

function sum(…numbers) {
  var result = 0;
  numbers.forEach(function (number) {
    result += number;
  });
  return result;
}

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

Spread

https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Operators/Spread_syntax

The spread operator is the opposite of rest operator. It allows you to expand an expression in places where you would expect multiple arguments (in functions) or multiple elements (in arrays).

let beers = ['Bitburger','Heineken'];
 
function logBeers (firstParameter, secondParameter) {
  return console.log(`${firstParameter} ${secondParameter}`);
}
 
logBeers(...beers); // output: Bitburger Heineken

Object Literal Extensions

Object Literals is a pattern for creating objects, with ES6 the syntax got extended.
Before ES6, object literals are constructed with two parts like stock: stock, this is mostly duplication. With ES6 we can remove this duplication as long as the local variable name is the same as the property of the object.

We also can define function methods directly without the usage of the function keyword.

var name = 'Beer';
var stock = 42;
var product = {
  name,
  stock,
  reduceStock(){
    this.stock--;
  }
}

console.log(product); // output: { name: 'Beer', stock: 42 }
product.reduceStock();
console.log(product); // output: { name: 'Beer', stock: 41 }

for ... of Loops

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of

The for of loop is the third variant of a for loop in JavaScript. Break and continue work inside of a for-of loop and you can iterate through a wide set of objects.

var beers = ['Pils','Weißbier','Weizen'];
for(var beer of beers){
  console.log(beer);
}

//output: Pils
//output: Weißbier
//output: Weizen

Template Literals

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

A template is a string template with interpolated variables and expressions. It is indicated with ``, the backtick character. The template literal can contain placeholders indicated by a dollar sign and curly braces ${beerName}. It is also possible to split template literals over multiple lines, keep in mind whitespaces like tabs and spaces are maintained.

let beerName = 'Bitburger';
let beerPrice = 1.50;

console.log(`The ${beerName} cost ${beerPrice}`);
// output: The Bitburger cost 1.5

let beers = `Bitburger
Bolten
Heineken
`;

console.log(beers);
// output: Bitburger
// output: Bolten
// output: Heineken

Destructuring

With destructuring, you can extract values from data stored in objects, you can destructure parameters, arrays, objects.

const beer = {
  name: 'Bitburger',
  price: 1.5,
  type: 'pils',
};

const { name, type } = beer;

console.log(name, type);
// output: Bitburger pils
const beer = ['Bitburger', 1.5, 'Pils'];
const [name, price, type] = beer;
console.log(name, price, type);
// output: Bitburger 1.5 Pils
function writeBeer({ name, type }){
  console.log(name)
  console.log(type)
}

let beer = {
  name: 'Bitburger',
  type: 'Pils'
}

writeBeer(beer);
// output: Bitburger
// output: Pils

I hope you enjoyed this post, stay tuned for the following posts about ES6.