JavaScript ES6 Fundamentals

Daniel Mocan

Software Developer @ Fortech

Meetup organizer @ JSHeroes

Twitter: @danielsmocan

Content

intro

let and const

template literals

default parameters

rest parameters

destructuring

spread operator

object enhancements

arrow function

class

What is ES6?

ES is a shortcut from ECMAScript. ECMAScript specification is a standardised specification for JavaScript language.

JavaScript had previous names: Mocha or LiveScript

Brendan Eich, developed JavaScript in 10 days back in 1995.

ES6 or ES2015 strands for ECMAScript 6

Let & Const

Before let and const, the only option was var.

Var has no block scope, only global or function scope.

Let

let name = "Vasile";

// not allowed because you are not able to redeclare it 
let name = "Ion";

// not allowed because its used before its declared
console.log(employeeName);
let employeeName = "Dani Mocanu";

{
    let employee = 'Calin';
}

// this will throw an error (Uncaught ReferenceError: employee is not defined )
console.log(employee); 

Variables defined with let:

cannot be redeclared

have block scope

must be declared before used

Const

const name = "Vasile";

// not allowed because you are not able to redeclare it 
const name = "Ion";

// not allowed because its used before its declared
console.log(employeeName);
const employeeName = "Dani Mocanu";

{
    const employee = 'Calin';
}

// this will throw an error (Uncaught ReferenceError: employee is not defined )
console.log(employee);

Variables defined with const have the same restrictions (*) :

cannot be redeclared

have block scope

must be declared before used

Const

const noValueChange = "Value";
noValueChange = "Changed Value"; //Uncaught TypeError: Assignment to constant variable.

const person = {
    name: 'Razvan',
    age: 25
};

// Works fine, but why?
person.position = 'AQA';
console.log(person);

(*) almost as let :

There is one important difference, the value cannot be changed after it was assigned.

Exercises

Arrow Functions

const sayHi = (name) => {
  console.log(`Hi ${name}`);
}
sayHi("Daniel");

Arrow functions are shorter and easier to read.

If the the arrow function recives only one argument you don't have to use the parentheses.

Also if the arrow function is not complex you can write it on one line.

const sayHello = name => console.log(`Hello, ${name}`);
sayHello("Andrei");

Exercises

Default Parameters

Gives you the option to add default values for the parameters sent to a function.

function addVAT(price, vat = 0.19) {
    return price + (price * vat);
}

const productPrice = 100;
const specialVAT = 0.10;
const productPriceWithVAT = addVAT(productPrice);
const productPriceWithSpecialVAT = addVAT(productPrice, specialVAT);

console.log('productPriceWithVAT', productPriceWithVAT);
console.log('productPriceWithSpecialVAT', productPriceWithSpecialVAT);

Exercises

Rest Parameters

Can collect all of them or only the ones on the right side.

const printDetails = (name,...res) => {
   console.log('Name', name);
   console.log('rest', rest);
}

const restFunc = (a,b, ...rest) => console.log(rest);

restFunc(1,2, 3, 4) // [3,4];
restFunc(1)// [] (empty array)

Rest Parameters

A few bad examples that will not work, and throw errors

const restExample = (...rest, a, b) => console.log(rest);

const anotherBadExample = (a, ...rest, b) => console.log(rest);

Exercises

Destructuring

const names = ['Daniel', 'Adina', 'Andrei'];
 
const [ daniel, adina, andrei] = names;

Destructuring allows you assign elements from an array.

You can also use rest parameters to collect a part of the elements from the array.

const names = ['Daniel', 'Adina', 'Andrei'];

const[daniel,...rest] = names;

console.log(rest);

Destructuring

const person = {
  name: 'Rodica',
  age: 25
}

const { name } = person;
console.log(name); //Rodica

const { name: renamedName } = person;
console.log(renamedName); // Rodica

You can use destructuring on objects.

Exercises

Spread Operator

The spread operator allows you to spread out elements of an iterable object like arrays.

const listOfEmployees = ['Loredan', 'Valentin', 'Norbert'];
const newHires = ['Dorin', 'Dan', 'Claudiu'];

// creates a new list with the updated employees
const updateEmployeesList = [...listOfEmployees, ...newHires];

Spread Operator

const person = {
  name: 'Vitalie',
  age: 25,
  department: 'HR',
}
const newPerson = {...person};
console.log(newPerson);

Spread operator for objects was introduced in es9 (es2019)

Exercises

Template Literals

ES6 template litterals allows you to work easier with strings.

const fullName = `Ion Popescu`;

For this we could have used single or double quotes!!!

const firstName = "Ion";
const lastName = "Popescu";

const fullName = `First Name: ${firstName} Last Name:${lastName}`;
console.log(fullName);

//No more
const fullName = "First Name: "+ firstName +"Last Name:"+ lastName;

Template Literals

You can do even more

const hours = 160;
const rate = 15;

console.log(`Your earnings in June: ${hours * rate} euro`);

Exercises

Object Enhancements

Initialization from variables

const name = 'Oana';
const age = 25;

// no more 
const person = {
  name: name,
  age: age,
}

// you can simply
const newPerson = {
  name,
  age
}

Object Enhancements

Shorthand definitions for object methods

const employee = {
  firstName: 'Loredana',
  lastName: 'Lasca',
  age: 25,
  getFullName: function() {
    return this.firstName +' '+ this.lastName;
  }
};

const newEmployee = {
  firstName: 'Oana',
  lastName: 'Ujica',
  age: 25,
  getFullName() {
    return `${this.firstName} ${this.lastName}`;
  }
};

Object Enhancements

Dynamic property keys

//Before
const objKey = 'name';

const person = {
  age: 25,
}
person[objKey] = 'Valentin';

//with es6 you can add them directly

const person = {
  age: 25,
  ['name']: 'Razvan',
}

Exercises

Classes

Class's are mostly syntactic sugar over prototypal inheritance, but they are a nice addition to JavaScript.

class Employee {
    constructor(name, age, department) {
        this.name = name;
        this.age = age;
        this.department = department;
    }
    getName() {
        return this.name;
    }
}

const newEmployee = new Employee('Adrian', 25, 'IT Support');
console.log(newEmployee);

Classes

Constructor is a special method that is used for creating and initializing the object with classes.

 constructor(name, age, department) {
    this.name = name;
    this.age = age;
    this.department = department;
 }

getName is a method on the object that returns the name of the employee.

getName() {
  return this.name;
}

Classes

Static Methods & Properties

class Names {
    static name = "This is a static property";
    static doubleName = (name) => `${name} ${name}`
}
console.log('Names.name ', Names.name);
console.log('Names.doubleName', Names.doubleName('Vasile'));

They are not available on a instance of the object.

Exercises

Summary

history of JS

arrow functions can improve readability 

the benefits of ... (dots) for rest, destructuring or spread

how template litterals helps us with strings

the importance of es6 features in js

the nice addition of let and const

we have seen classes in action

What did you found useful / interesting?

Feedback

Multumesc

Made with Slides.com