+1

Some new features of ES6, I mean ES2015

ECMAScript 2015 (previously ES6) is the newest version of the ECMAScript standard. It is a significant update to the language, and the first major update to the language since ES5 was standardized in 2009. Implementation of these features in major JavaScript engines is underway now. Though, currently no web browsers support ES6 directly, but there are a lot of transpilers (eg Babel) that does the conversation for the browser excellently. Here are some new features that will come in handy while coding.

'let' is the new 'var'

So what do you think this block of code will print after executed?

var name = "JOSIM";

if(true) {
  var name = "Sodrul";
  console.log(name);
};

console.log(name);

In general logic, it should've printed

Sodrul
JOSIM

Correct? As, we declared name to be "JOSIM" outside the if block, we'd expect it won't change after whatever we do inside another block, right?

Wrong !! This is one of the weired features of JS (after all, the language was written in just 2 weeks, #BRANDENISBOSS)

When executed, this code behaves like,

var name = "JOSIM";

if(true) {
  name = "Sodrul";
  console.log(name);
};

console.log(name);

and prints this as output.

Sodrul
Sodrul

(-_-) I know, Right? WTF JavaScript?

The 'let' keyword is going to fix this issue.'let' allows you to declare variables limited in scope to the block, statement or expression on which its being used. It's slightly different from the 'var' keyword, which defines variables globally (or locally to an entire function regardless of block scope).

So, this code should behave exactly as you thought,

let name = "JOSIM";

if(true) {
  let name = "Sodrul";
  console.log(name);
};

console.log(name);

and print

Sodrul
JOSIM

You can test the live code here.

However, unlike var, 'let' does not create a property on the global object.

Like this example.

var x = 'Salekin';
console.log(this.x); // Salekin

let y = 'Salekin';
console.log(this.y); // Undefined

Also, redeclaring the same variable within the same function or block scope will raise SyntaxError.

Example

if(true) {
  let x;
  let x; // SyntaxError thrown, Duplicate declaration "x"
}

For indepth discussion read MDN

Constants

This might sound funny, but the concept of constant is new in javascript. As we all know, const means that the variable can’t be reassigned. (Not to be confused with immutable values. Unlike true immutable datatypes such as those produced by Immutable.js and Mori, a const object can have properties mutated.) Example

Also, here's a good discussion board for Immutable.js vs Mori

const PI = Math.PI;
const PI = Math.PI;
PI = 100; // will raise error, "PI" is read-only

Constants are block-scoped, much like variables defined using the let statement. The value of a constant cannot change through re-assignment, and it can't be redeclared. Example

const PI = Math.PI;
const PI = 1010101; // will raise error, Duplicate declaration "PI"

Template Literals

Strings in JavaScript was kind of limited, lacking the capabilities one might expect coming from Ruby. ES6 Template Literals, fundamentally change that. They can be used for:

  • String Interpolation
  • Embeded expressions
  • Multiline Strings (without any hacks)
  • String formatting
  • String tagging for safe HTML escaping, logalization etc.

Here's an example of String interpolation: You have to enclose the string with back ticks `` to get this feature

var greet = function(name) {
 console.log(`Hello ${name}`);  // just like ruby #{}
}

greet("josim"); // prints "Hello josim"

Example of Multiline strings:

let x = `string text line 1
string text line 2`;

console.log(x);

will actually produce the code:

var x = "string text line 1\nstring text line 2";
console.log(x);

and output

string text line 1
string text line 2

For detail explanation, read this article by Addy Osmani

Extended Parameter Values

In ES6 you can declare default values of your parameters very easily.

function f (x, y = 2, z = 3) {
  return x + y + z
};

f(1) // 6  (1 + 2 + 3)

which was a bit tedious in previous JS versions, (-_-)

function f (x, y, z) {
  if (y === undefined) {
    y = 7;
  }
  if (z === undefined) {
    z = 42;
  }
  return x + y + z;
};

Binary and Octal literals

You now have direct support for safe binary and octal literals in ES6

0b10 //  2 (binary)
0o12 // 10 (octal)

which is pretty and more consice than what you needed to do in previous versions:

// This is what you needed to do in previous versions.
parseInt("10", 2) //  2
parseInt("12", 8) // 10

Arrow =>

The most fun feature of ES6 yet is the arrow function. An arrow function expression has a shorter syntax compared to function expressions. Example

let numbers = [1,2,3,4,5,6,7];
let squared = numbers.map(v => v*v); // [1,4,9,16,25,36,49]

which makes the code concise and elegant. Trying to achieve the same with previous language version whould be like,

// previous js code to do the same
var numbers = [1, 2, 3, 4, 5, 6, 7];
var squared = numbers.map(function (v) {
  return v*v;
});

If a function has multiple parameters, it can be written as

var multiply = (x, y) => x*y;
multiply(2,3); // 6

Also, consider this example, which returns a JSON object after given the appropriate inputs.

let setNameIdsEs6 = (id, name) => ({ id: id, name: name });

which would look like this if tried in language prior ES6

var setNameIdsEs6 = function setNameIdsEs6(id, name) {
  return {
    id: id,
    name: name
  };
};

YOU SEE HOW COOL IS THAT !!

It's almost as fun as hearing the French pronounciation of the word Vanilla Chocolate for the first time (^_^)

One thing to note though, Arrow functions will always be anonymous.

To read more about them please visit MDN

End of Part One

So, these were some of many fun and useful new features to come in ES6, I hope to continue more this on my next article. Till then Happy Coding.

If you're still wondering how the French pronounce Vanilla Chocolate


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí