Introduction

What is ES?

  • ES stands for ECMAscript
     
  • ECMA is an organization that standardizes information

What is the relation?

ECMAscript is a standard.

 

JavaScript implements ECMAScript as standard and builds on top of it.

ES1, ES2, ES3, ES4

ES1: June 1997

ES2: June 1998

ES3: Dec. 1999

ES4: Abandoned

ES5

December 2009​

 

List of feature:

http://kangax.github.io/compat-table/es5/

ES6/ES2015

June 2015

 

List of features: 

http://kangax.github.io/compat-table/es6/

let & const

Cons of var

  • Possible to easily pollute the global scope
     
  • Not block-scoped

const

  • The value remains constant
     
  • Cannot be re-assignment or redeclared
     
  • Can be declared uppercase (recommended!) or lowercase
     
  • Block-scoped

example const

// declaring a const
const FOO = 'bar';
// Array
const GAMES = ['AC: Origins'];

// Push method to modify the array
GAMES.push('CoD: WWII');
console.log(GAMES);

// Output:
['AC: Origins', 'CoD: WWII']
// Object
const CAR = {
    brand: 'VW',
    color: 'red'
};

// Using dot notation to modify the object
CAR.year = '2017';
console.log(CAR);

// Output:
{brand: 'VW', color: 'red', year: '2017'}

error const

// declaring a const
const BAR = 'bar';

// try to re-asign a const
const BAR = 'foo';

// Error
// Identifier 'BAR' has already been declared

// try to change value of a const
BAR = 'foo';

// Error
// Assignment to constant variable

let

  • Block-scoped
     
  • Allows you to re-assign a value
     
  • Should use camelCase

example let

// declaring a let
let foo = 'bar';


// Avoids scoping problems in for loops because it's block-level scoped
for ( let i = 0; i < 10; i++ ) {
  console.log(i);
}


(function() {
    let fooBar = 'foo';

    (function() {
        // Scope 1
        let fooBar = 'bar';
        console.log('scope 1: ', fooBar); // Is 'bar'
    }());

    console.log('Parent scope: ', fooBar); // Is 'foo'

}());
console.log('Global scope: ', fooBar); // Is undefined

error let

// declaring a let
let bar = 'bar';

// try to re-asign a const
let bar = 'foo';

// Error
// Identifier 'bar' has already been declared

Arrow function

Arrow function

  • Shorter syntax than normal function
     
  • The arrow function get it's 'this' from the parent
     
  • not have its own

Example 1

const exampleFunction = () => {
    // Arrow function
    return 'arrow!';
}
function exampleFunction() {
    // Normal function
    return 'arrow!';
}

>

Example 2

const exampleArray = [...];

exampleArray.map(function(item) {
    // item
})
const exampleArray = [...];

exampleArray.map(item => {
    // item
})

// or

exampleArray.map((item, index, arr) => {
    // item, index, arr
})

>

Events!!

element.addEventlistener('click', function(event) {
    // event
    console.log('demo1 event: ', event);
    console.log('demo1 this: ', this);
});
element.addEventListener('click', event => {
    // event
    console.log('demo2 event: ', event);
    console.log('demo2 this: ', this);
});

Events !!

Template literals

Template literals

// Example: String literal
const DEV_QUOTES = 
    '<ul>' + 
        '<li>It’s not a bug. It’s an undocumented feature!</li>' + 
        '<li>Things aren’t always #000000 and #FFFFFF</li>' + 
        '<li>Beta is Latin for "still not working"</li>' + 
    '</ul>';


// Example: Template literal
const DEV_QUOTES = `
    <ul> 
        <li>It's not a bug. It’s an undocumented feature!</li>
        <li>Things aren't always #000000 and #FFFFFF</li> 
        <li>Beta is Latin for "still not working"</li>
    </ul>
`;



// Interpolation
let nameDeveloper = `Chuck`;
let companyName = `Competa`;

let joinUs = `Hi ${nameDeveloper}, come join our Tech Talk on the 22nd at ${companyName}`;

Searching strings

Searching strings

Methods

  • startsWith
     
  • endsWith
     
  • includes
let quote = 'There are two ways to write error-free 
programs; only the third one works.';

console.log(quote.startsWith('There are'));

// Possible to give a parameter with the position you want to start indexing
console.log(quote.startsWith('There are', 2));

// Example regular expression
console.log(/^There/.test(quote));

startsWith

Checks if a strings begins with a particular set of characters

let quote = 'A good way to stay flexible is to write less code';

console.log(quote.endsWith('code'));

// Possible to give a parameter to indicate the maximum characters to search through
console.log(quote.endsWith('code', 10));

// Example regular expression
console.log(/code$/.test(quote));

endsWith

Checks if a strings ends with a particular set of characters

let quote = 'A good way to stay flexible is to write less code';

console.log(quote.endsWith('code'));

// Possible to give a parameter to indicate the maximum characters to search through
console.log(quote.endsWith('code', 10));

// Example regular expression
console.log(/code$/.test(quote));

includes

Check if a string includes the word

Default, rest & spread

Default parameter

function multiply(a, b) {
    b = b || 1;
    return a * b;
}

console.log(multiply(5, 2));
// expected output: 10

console.log(multiply(5));
// expected output: 5

You can set default values to function parameters.

ES5

function multiply(a, b = 1) {
  return a * b;
}

console.log(multiply(5, 2));
// expected output: 10

console.log(multiply(5));
// expected output: 5

ES6

Rest parameter

When adding "..." as latest parameter, this parameter will become an Array.

function looping(a, b, c) {
    if(Array.isArray(c)) {
        // you have to check if it's an Array
    }
}

var numbersArray = [1, 2, 3, 4, 5];

looping(1, 2, numbersArray);

ES5

function(a, b, ...theArgs) {
  // by default it's an Array
}

var numbersArray = [1, 2, 3, 4, 5];

looping(1, 2, numbersArray);

ES6

Spread syntax

When adding "..." as parameter, the Array will fill the arguments.

function sum(x, y, z) {
  return x + y + z;
}

var numbers = [1, 2, 3];

console.log(sum.apply(null, numbers));
// expected output: 6

ES5

function sum(x, y, z) {
  return x + y + z;
}

const numbers = [1, 2, 3];

console.log(sum(...numbers));
// expected output: 6

ES6

Spread syntax

😁 Make an Array of (almost) everything!! 😁

// String to Array
const title 'This is a test!';

console.log([...title]);
// Output: ["T", "h", "i", "s", " ", "i", "s", " ", "a", " ", "t", "e", "s", "t", "!"]

// Merging Arrays
const testArray = [1, 2, 3];
console.log([...testArray, '4', 'five', 6]);
// Output  [1, 2, 3, "4", "five", 6]
const competaObject = {
    title: 'This is a test',
    id: 587
}

const cloneCompeta = {...competaObject}
// Output: {title: "This is a test", id: 587}

competaObject.name = 'Competa IT';

console.log(competaObject);
// Output: {title: "This is a test", id: 587, name: "Competa IT"}
console.log(cloneCompeta);
// Output: {title: "This is a test", id: 587}

Spread syntax

😁 Cloning Objects (without reference)!! 😁

Not for Array's with Objects!

var dateFields = [1970, 0, 1];  // 1 Jan 1970
var d = new Date(...dateFields);

Spread syntax

😁 Use it as parameter on a Date!! 😁

Synchronous and Asynchronous

You click on a button, immediately this will follow with an action

Synchronous

You click on a button, it will send a get request to the Github API, but you don't know when the result will come back

Asynchronous

Difference

Sync Async
Action will be executed immediately. For example: eventlistener Action will happen, but you don't know when. For example: Ajax call

Promises

What is a Promise

The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.
Source: MDN docs

Promises states

A promise can have 3 types of states:

 

  1. Pending: Initial state. Not fulfilled, not rejected
  2. Fulfilled: The operation successfully completed
  3. Rejected: The operation was rejected because of an error

Create a Promise

function asyncAJAX(url) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open("GET", url);
    xhr.onload = () => resolve(xhr.responseText);
    xhr.onerror = () => reject(xhr.statusText);
    xhr.send();
  });
}

Use a Promise?

asyncAJAX('https://api.github.com/users/raymonschouwenaar')
    .then(result => {
        console.log('result: ', result);
    }, error => {
        console.error('error: ', error);
    })

Promise steps

asyncAJAX('https://api.github.com/users/raymonschouwenaar')

After the funtion is called

.then(result => {
    console.log('result: ', result);
}, error => {
    console.error('error: ', error);
})

A Promise is returned with the status "Pending".

When the server gives back a response, the then will be called which will return a result (status "Fulfilled") or an error (status "Rejected")

function asyncAJAX(url) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open("GET", url);
    xhr.onload = () => resolve(xhr.responseText);
    xhr.onerror = () => reject(xhr.statusText);
    xhr.send();
  });
}
asyncAJAX('https://api.github.com/users/raymonschouwenaar')
    .then(result => {
        console.log('result: ', result);
    }, error => {
        console.error('error: ', error);
    })

When you should use Promises?

Use a Promise only when a operation is asynchronous.

Example: Ajax requests

THE END

JavaScript (ES6) - Part 1

By CodePamoja

JavaScript (ES6) - Part 1

  • 126