Skip to content

Instantly share code, notes, and snippets.

@hlrd93
Last active January 19, 2017 05:23
Show Gist options
  • Save hlrd93/6a22546bfcd7eaccee114799b4c15b43 to your computer and use it in GitHub Desktop.
Save hlrd93/6a22546bfcd7eaccee114799b4c15b43 to your computer and use it in GitHub Desktop.
ES6en
#**ES6:** *First Episode.
###Introduction
Brendan Eich created a language called Mocha in 1995, when he worked on **Netscape**. Then, its name was changed to **LiveScript** in September of the same year. Nevertheless, this title was reformed too, for the reason that a commercialization emerged. **Netscape** was obtained by **Sun Microsystems**, owner of Java language.
Later in 1997 appeared the **ECMA (European Computer Manufacturers Association)**, a committee to standardize *JavaScript*. The standard is planned to avoid incompatibilities between browsers. Since then, *JavaScript* guidelines are run by *ECMAScript*.
At the beginning of 1999, the *ECMAScript* guideline third version is generated. It would remain usable for a few years more; next, some attempts were made to write the fourth version. However, it was only until 2011 that the fifth version *(ES5)* was approved and standardized.
Consequently in 2013, the sixth version project was stopped until December 2014. Finally, the project was approved and standardized in June 2015. In this way, *ECMAScript2015* was situated as the latest version of *JavaScript* programming language for the web. Focused on simplicity and legibility, it was named as *ES6* and it might be used in modern browsers.
Check out these links:
>*ECMAscript/ES6 features*
https://github.com/lukehoban/es6feature
>*Compatible table of browsers with ECMAscript2015 *
http://kangax.github.io/compat-table/es6/
>*Intro ECMAscript2015/ES6*
https://medium.com/ecmascript-2015/let-s-talk-about-javascript-ecmascript-2015-es6-say-hello-world-658ce6941
###Prerequisites
So, let’s get started:
Install node from:
>https://nodejs.org/en/
***Or*** follow this guide:
You should have some familiarity with the Linux terminal since you will need to use it to install and test Node and NPM. You will also require the terminal to handle Node.js and NPM.
Dependencies: You need to install a number of dependencies before you install Node.js and NPM.
Ruby and GCC: You will have need for Ruby 1.8.6 or fresher and GCC 4.2 or newer.
For Ubuntu or Debian-based Linux distributions, run the following command in your terminal:
>***$*** sudo apt-get install build-essential curl git m4 ruby texinfo libbz2-dev libcurl4-openssl-dev libexpat-dev libncurses-dev zlib1g-dev
Then select Y to continue and wait for the packages to be installed.
For Fedora based Linux distributions run the following command in your terminal application:
>***$*** sudo yum groupinstall ‘Development Tools’ && sudo yum install curl git m4 ruby texinfo bzip2-devel curl-devel expat-devel ncurses-devel zlib-devel
Then select Y to carry on and wait for the packages to be installed.
**Homebrew:** Homebrew is a package manager originally for the Mac, but it has been ported to Linux as Linuxbrew, making installing most open-source software (like Node) as simple as writing: brew install node.
You can learn more about Homebrew at the Homebrew website and Linuxbrew at the Linuxbrew website.
To install Homebrew for Linux, open your terminal application and paste in the command:
>ruby -e “$(curl -fsSL
https://raw.githubusercontent.com/Homebrew/linuxbrew/go/install)”
Follow the instructions in the terminal to complete the installation process.
Once Linuxbrew is installed, you will need add the following 3 lines to your ~/.bashrc or ~/.zshrc file:
>`export PATH="$HOME/.linuxbrew/bin:$PATH"
>export MANPATH="$HOME/.linuxbrew/share/man:$MANPATH"
>export INFOPATH="$HOME/.linuxbrew/share/info:$INFOPATH"`
####Why Homebrew/Linuxbrew?
You may be asking why you should use a third-party package manager. Here are some advantages:
- Can install software to a home directory and does not require sudo.
- Install software not packaged by the native distribution.
- Install up-to-date versions of software when the native distribution is old.
- Use the same package manager to manage both your Mac and Linux machines.
#**ES6:** *Second episode
###Installation
Installing Node.js and NPM is pretty straightforward using Linuxbrew, the Linux port of Homebrew. It handles downloading, unpacking, compiling, and installing Node and NPM on your system. After you have Linuxbrew installed, the whole process should only take you a few minutes.
Open up your terminal and type
>***$*** brew install node.
Sit back and wait. Homebrew has to download some files, compile and install them. But that’s it.
Then open a new terminal:
run command **node** like this:
>$ node
> `>`let h = "Hello DailyDrip"
> `>`
> `>`console.log(h)
'Hello DailyDrip'
###ES6 Syntax
Let’s play with **REPL** ( Read Eval Print Loop )
We have new *ES6* syntax as:
###**Template Strings**
The *template strings* are literal strings of text that are inserted in the source code.
With the new version *ES6* it is possible to include *strings* in a simpler way that it has been done until at the moment.
###**Syntax**
It involves of two fundamental aspects:
- **Inverted quotes (`)**, are used to determine the strings.
- The **dollar sign ($)** followed by **braces {}**, are used to add placeholders.
For example:
```javascript
//ES6
let object1 = "JavaScript";
let object2 = "awesome";
console.log(`I just want to say ${object1} is ${object2`);
// I just want to say JavaScript is awesome
```
#####**Multi-line strings**
In *JavaScript* you can use *multi-line strings*; in version *ES5* you could have these *multi-line strings* connecting with +.
We can see the difference between the previous version and the new version *ES6*.
As example:
```javascript
//ES5
var greeting = "how " +
"are " +
"you? ";
```
```javascript
//ES6
var greeting = "how
are
you?";
console.log("how
are
you?");
```
##// A //
####**String Interpolation**
The *interpolation strings* implants expressions within normal strings.
Any valid expression in the language, it is in the sheet.
As example:
***Arrays***
```javascript
//Arrays
var italian = [ 'la', 'donna', 'e', 'mobile' ];
console.info( `My chain joined: ${ italian.join( ' ' ) }` );
// my chain joined: la donna e mobile
```
***Objects***
```javascript
// Objects
var library = [
{ id: 1,
title: 'Harry Potter'},
{ id: 2,
title: 'The Secret' }
];
var myID = 2;
console.info( `Book title: ${ library.find( item => item.id === myID ).title }` );
// Book title: The Secret
```
***Methods***
```javascript
// Methods
var sentence = 'the house is big';
console.info( `Uppercase: ${ sentence.toUpperCase() }` );
// Uppercase: THE HOUSE IS BIG
```
***Math***
```javascript
//Math
var value1 = 1000,
value2 = 200;
console.info( `The sum: ${ valor1 + valor2 }` ); // 1200
```
***Ternary Operator***
```javascript
//ternary operator
var book = {
id: 10,
title: false,
year: 2011
};
console.info( `Book report: ${ book.title ? book.title : 'Missing book title!' }` );
// Book report: Missing book title!
```
***Logical operators***
```javascript
//Logical Operator
var book = {
id: 11,
title: 'Narnia',
year: false
};
console.info( `Book year: ${ book.year || 'Unkonwn' }` );
// Book year: Unknown
```
#####**Post-processing Templates **
A *post-processing function* is a more advanced form of *template strings*, which is known as a *quasi-parser* role.
With this, you can achieve modifying the templates output, using a function.
Example:
```javascript
var tag = strings => console.log(strings);
tag`Hello World`;
// [ "Hello World" ]
```
The ***`tag`*** function, called *quasi-parser*, it is responsible for collecting a String parameter ***`string`*** giving the same value as output. When making the call to the function instead of using the parenthesis as it has been usually done, we do it with a text template *(quasi-quotation)*.
As a result, ***`tag`*** receives the template as an argument and displays it on the screen, for
Example:
```javascript
var tag = function ( strings ) {
return strings;
};
var result = tag`Hello World`;
console.info( result );
// [ "Hello World" ]
```
Therefore, the function gathers the literals, and the interpolation is achieved through the other parameters.
```javascript
var tag = function ( strings, ...values ) {
console.info( strings );
console.info( values );
};
var name = 'Carlos',
city = 'Canada';
tag`Hello ${ name }, Welcome to ${ city }!`;
// [ "Hello ", ", Welcome to ", "!" ]
// [ "Carlos", "Canada" ]
```
It can be noticed that a new argument has been added to the ***`tag`*** function, basically, what has been done is to group all the ones that arrive from the second, by the arraying operator, and that ***`array`*** collects the values that are obtained from the interpolation.
###**Block scoping: var vs let vs const**
As a consequence of the short time in which the *JavaScript* language was developed, it did not have *blockScoping*, being ***`var`*** the only keyword for the variables until now. With the new *ES6* version, two new procedures for the variables statement in *JavaScript* are accessible:
***`let`*** and ***`const`***.
>***note:***
>1. Use ***`const`*** by default
>2. Use ***`let`*** if you have to rebind a variable.
>3. Use ***`var`*** to signal untouched legacy code.
####**Syntax:**
####**let: **
One of the new tendencies in *ES6* is ***`let`***, which allows to declare variables by limiting their *scope* to the block, the expression where it is being used, that might optionally be initialized with some value.
This is what makes different the ***`let`*** expression of the reserved word ***`var`***.
This defines a global or local variable in a function, regardless of the scope of the block.
Example:
```javascript
//if
(function(){
var vegetable = "carrot";
if(true){
console.log(vegetable);
let vegetable = "Potato";
console.log(vegetable);
//Potato
}
console.log(vegetable);
//carrot
})();
```
It can be seen in the example that when we use ***`let`*** in a block, we can limit the space of variables in this block. It is viable to note the variance of a and ***`var`***, whose range remains within the function where the variable has been declared.
**For loop block**
```javascript
for(let i = 0; i < 30; i++){
console.log(i);
}
console.log("outside" + i); //Undefined
for(var i = 0; i < 30; i++){
console.log(i);
}
console.log("outside" + i); //30
```
##// B //
####**Const:**
***`Const`*** is the other *ES6* new statement for variable declaration; the declaration of ***`const`*** creates a constant that can be global or local to the function in which it is declared, that is to say it is necessary to initialize the constant, specifying its value in the same statement in which it is affirmed.
That value cannot be changed through reassignment and cannot be re-stated.
Ejemplo:
```javascript
const varname1 = value1 [, varname2 = value2 [, varname3 = value3 [, ... [, varnameN = valueN]]]];
```
>***note:**
>When declaring a ***`const`***, a read-only reference is created, this does not mean that the value is immutable, but the identifier of the variable cannot be reallocated, in the case that the assignment to the constant is an object, the object can be altered.
>
>A constant cannot share its name with a function or variable in the same scope.
> The ***`integer`***, ***`strings`***, ***`Booleans`***, ***`symbols`***, ***`null`*** or ***`undefined`***, that is, primitive values are always absolute.
####**var:**
*JavaScript* variables are containers for storing data values.
Example:
```javascript
var A = 20;
var B = 50;
var C = A + B;
// A stores the value 20
// B stores the value 50
// Then C the value 70
```
All *JavaScript* variable must be identified with exclusive names termed *identifiers*, they could be short designations as letters or more descriptive names as some characteristic (name, age…).
>***nota:***
>Using ***`var`*** outside of a function is somewhat optional, assigning a value to an undeclared variable implies that it is confirmed as a global variable.
```javascript
var varname1 [= value1 [, varname2 [= value2 ...[, varnameN [= valueN ']]]]];
```
>***`note:`*** It is constantly recommended to use ***`var`***, and it is crucial within functions in the following situation:
>1. When a variable in a scope contains the function including also the global scope and it has the same name.
>2. When several functions or recursive functions use variables with the same name and are intended to be local.
>3. When not declaring the variables in these cases can lead to unwelcome outcomes.
###**Functions**
##// C //
###**Arrow Functions**
The *arrow functions* are, as the name suggests, functions defined with a new syntax that uses an arrow ***`(=>)`***.
It is a new way of writing anonymous functions, being a new syntax in the final version of *ES6* standards. It is a simple change that allows us a faster and cleaner way of producing an anonymous function, as well as saving time and simplifying development in the scope of the function.
In the previous *ES5* version, an anonymous function has been written like this:
```javascript
// ES5
var AddAB = function (A, B) {
r eturn A + B;
}
```
This does not seem too long, however, we can now abbreviate our code even further with the new *ES6* form to this:
```javascript
// ES6
var AddAB = (A, B) => A + B;
```
Something interesting about *arrow functions* is the use of ***`this`***, they change the way this joins in functions.
>***note:***
>After the parameters, it is where the arrow is placed followed by the variable that has been shown.
>We have been able to set aside the return instruction, since that feedback is over understood by writing it in this way.
>You can remove the need to bind this to the function.
####**Limitations:**
However *arrow functions* behave differently than traditional JavaScript functions in certain important ways:
1. ***`super`***, ***`arguments`***, and ***`new.target`***, these values within the function are defined by the closest one that does not contain the *arrow function*.
2. They cannot be called new *arrow functions* if do not have a ***[[Construct]]*** method and therefore cannot be used as constructors. *Arrow functions* throw an error when used with new ones.
3. It is not necessary to use prototypes for the *arrow functions*, since prototypes do not exist for arrow function.
4. You cannot change the value inside the function. This value will persist the same for the entire life cycle of the function.
5. No *arguments could be objected* because *arrow functions* have no arguments binding, you must rely on ***`name`*** and the ***`rest`*** of parameters to access function arguments.
6. In the duplicate named parameters, functions cannot have duplicate ***`name`*** parameters in strict or non-strict mode, as opposed to *arrow functions*, which cannot have duplicate named parameters in strict mode.
####**Syntax:**
The syntax for the *arrow functions* comes in several forms depending on what it is going to try to achieve. All variations begin with the arguments of the function, followed by the arrow, followed by the body of the function.
Arguments and the body can take different forms depending on the use.
For example:
The following *arrow function* takes a single argument and simply returns it:
```javascript
let reflect = value => value;
// effectively equivalent to:
let reflect = function(value) {
return value;
};
```
If you are passing more than one argument, you must include parentheses around those arguments, like this:
```javascript
let sum = (obj1, obj2) => obj1 + obj2;
// effectively equivalent to:
let sum = function(obj1, obj2) {
return obj1 + obj2;
};
```
If there are no arguments to the function, you must include an empty set of parentheses in the statement, as follows:
```javascript
let getName = () => "DailyDrip.com";
// effectively equivalent to:
let getName = function() {
return "DailyDrip.com";
};
```
When you want to provide a more traditional function body, perhaps consisting of more than one expression, you need to wrap the function body in *curly braces* and explicitly define a return value, as in this version *ES6* of ***`sum()`***:
```javascript
let sum = (number1, number2) => {
return number1 + number2;
};
// effectively equivalent to:
let sum = function(number1, number2) {
return number1 + number2;
};
```
If you want to create a function that does not do anything, you need to include *curly braces*, like this:
```javascript
let doNothing = () => {};
// effectively equivalent to:
let doNothing = function() {};
```
**Syntax quirks**
>Points to take into account respect to syntax. .
>1- => Cannot be used as constructor functions, by means of the new procedure of writing, it generates an error.
```javascript
new ()=>{} // invalid
new (()=>{}) // invalid
```
>2- The line break after the parameters is not valid in the *arrow functions*, it is only valid if it is defined inside the parameter.
```javascript
const function1 = (A, B) // SyntaxError
=> {
return A + B;
};
const function2 = (A, B) => // OK
{
return A + B;
};
const function3 = (A, B) => { // OK
return A + B;
};
const function4 = (A, B) // SyntaxError
=> A + B;
const function5 = (A, B) => // OK
A + B;
// Line breaks inside parameter definitions are OK:
const func6 = ( // OK
A,
B
) => {
return A + B;
};
```
###**Object literals**
*Object Literals* is something that *JavaScript* developers are very familiar with if they have worked with *JSON* since this is based on whose syntax; *object literals* is one of the most popular patterns in *JavaScript*.
*ECMAScript 6* makes *object literals* more powerful and even more concise by extending the syntax in several ways.
####**Syntax**
**Property Initializer Shorthand **
Beforehand the expression representing the *property initializer shorthand* was as follows, example:
```javascript
//ES5
function createSpecies(name, tipe) {
return {
name: name,
tipe: tipe
};
}
```
The ***`createSpecies ()`*** function creates an object whose property names are the same as the function parameter names. The key ***`name`*** in the returned object is assigned to the value that contains the variable ***`name`***, and the value of the ***`tipe`*** key in the returned object is dispensed to the value contained in the variable ***`tipe`***.
***`createPerson ()`*** can be rewritten for *ECMAScript 6* as follows:
```javascript
//ES6
function createSpecies(name, tipe) {
return {
name,
tipe
};
}
```
In this example, the name of the *object literals* property is mapped to the ***`name`*** of the local variable, which is a very common *JavaScript* pattern.
**Concise Methods**
To express *concise methods* in *ECMAScript 5* and previous, a name must be specified, and then defining the complete function to add a method to an object.
For example:
```javascript
//ES5
var pets = {
name: "Duck",
sayName: function() {
console.log(this.name);
}
};
```
In version *ES6* the syntax is simplified making it shorter, so it is called syntax of *concise methods*, excluding the colon and the function keyword.
For example:
```javascript
//ES6
var pets = {
name: "Duck",
sayName() {
console.log(this.name);
}
};
```
>***note:***
>The property name of a method created using the concise method contraction, is the name before the parentheses.
**Computed property names**
For *ES5* version these properties were fixed with brackets instead of dot notation, for this mentioned reason, brackets allow you to specify the names of properties using *vars* and *string literals* that may contain characters that cause syntax errors.
Example:
```javascript
var student = {},
lastName = "last name";
student["first name"] = "Angela";
student[lastName] = "Alvarez";
console.log(student["first name"]);
console.log(student[lastName]);
// "Angela"
// "Alvarez"
```
You can also use *string literals* in a direct way as a property name in *object literals*.
As it is seen:
```javascript
//ES5
var student = {
"first name": "Angela"
};
console.log(student["first name"]);
// "Angela"
```
For *ES6* brackets are also used to allusion calculated property *names* on object instances.
For example:
```javascript
//ES6
let lastName = "last name";
let student = {
"first name": "Angela",
[lastName]: "Alvarez"
};
console.log(student["first name"]);
console.log(student[lastName]);
// "Angela"
// "Alvarez"
```
It also includes expressions where brackets within the *literal object* point to that the *name* property is calculated, so its contents are evaluated as a string.
As it is seen:
```javascript
var suffix = " name";
var student = {
["first" + suffix]: "Angela",
["last" + suffix]: "Alvarez"
};
console.log(student["first name"]);
console.log(student["last name"]);
// "Angela"
// "Alvarez"
```
Anything that is placed inside the brackets while using the bracket notation on object instances, also works for the *computed names* property inside *object literals*.
####**New Methods**
At present *ECMAScript 6* introduces a couple of new methods into the global object that are designed to make certain tasks easier.
**The Object.is() Method**
When it is wanted to compare two values in *JavaScript*, it is likely that the equal operator ***(==)*** or the identically equal operator are used ***(===)***.
Although the preference for accuracy leads developers to use the operator that is identical, however, this is not as accurate as it would be wish it was like, which is why *ECMAScript 6* introduces the ***`Object.is ()`*** method to solve this problem.
This method accepts two arguments and returns *true* if the values are equivalent. Two values are considered equivalent when they are of the same type and have the same value.
For example:
```javascript
console.log(+0 == -0); // true
console.log(+0 === -0); // true
console.log(Object.is(+0, -0)); // false
console.log(NaN == NaN); // false
console.log(NaN === NaN); // false
console.log(Object.is(NaN, NaN)); // true
console.log(3 == 3); // true
console.log(3 == "3"); // true
console.log(3 === 3); // true
console.log(3 === "3"); // false
console.log(Object.is(3, 3)); // true
console.log(Object.is(3, "3")); // false
```
**The Object.assign() Method **
***`Object.assign ()`*** takes care of accepting any *supplier* number and the recipient receives the properties in the order in which they are specified, i.e., the last *supplier* could overwrite a value from the first *supplier* in the receiver.
As it is shown:
```javascript
var receiver = {};
Object.assign(receiver,
{
type: "js",
name: "file.js"
},
{
type: "css"
}
);
console.log(receiver.type); // "css"
console.log(receiver.name); // "file.js"
```
The value of *receiver.type* is ***`"css"`*** because the second supplier has overwritten the value of the first.
The ***`Object.assign ()`*** method is not a significant addition to *ECMAScript 6*, but it does formalize a common function found in many *JavaScript* libraries.
## // D //
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment