Notes

[ES2015] ES6 Features Overview

Edit on GitHub

JavaScript
5 minutes

ES6 Features (ES2015)

Arrow Function Syntax

Arrow function syntax is supported in all major browsers.

 1// Function Declaration
 2function divide1(a,b) {
 3	return a/b;
 4}
 5
 6// Function Expression
 7const divide2 = function(a,b) {
 8	return a/b;
 9}
10
11// Arrow Function Expression
12const divide3 = (a,b) => {
13	return a/b; 
14}
15
16// Arrow Function Concise
17const divide4 = (a,b) => a/b;

Arrow (aka lambda) functions define the function to the instance of wherever it was created (or something like that, requires citation). The benefit of this is that in React when defining event handler functions, you no longer have to specifically bind them in the render() method.

1handleClick = (e) => {
2  e.preventDefault()
3}
4
5render() {
6  <button onClick={this.handleClick} />
7}

instead of

1function handleClick(e)  {
2  e.preventDefault()
3}
4
5render() {
6  <button onClick={this.handleClick.bind(this)} />
7}

They also make writing code for Promises a lot easier.

let and const

let is the new var. const is a single-assignment, meaning you only define it once, it won’t change.

For example

1let x = 15
2
3const React = require('react')
4const ReactDOM = require('react-dom')

Rest parameters ... and Spread operator ...

Rest parameters and spread operator look the same but achieve different things. A rest parameter collects the arguments passed to a function while the spread operator expands an array or any type of an expression.

Rest parameters ...

...params

The three dots ... before define a rest parameter, you can call it anything you want. It has to be the last parameter in the arguments

Returns an array of arguments

1const myFunc = (name, ...params) => console.log(name, params)
2myFunc('Andrew', 1, 2, 3, 4, 'Elephant') // Andrew [1,  2, 3, 4, 'Elephant']
1const myFunc = (...params) => console.log(params)
2myFunc('Andrew', 1, 2, 3, 4, 'Elephant') //  [ 'Andrew', 1,  2, 3, 4, 'Elephant']
1let flavorFunc = (name, iceCreamFlavor) => console.info(`${name} really likes ${iceCreamFlavor} ice cream`)
2
3let args = ['Aamnah', 'Pistachio']
4
5flavorFunc(...args) // Aamnah really likes Pistachio ice cream

Spread operator ...

...array or ...object

Bable ES2015 preset suports the Array spread but not the Object spread, since object spread is not part of ES2015 standard, it’s a stage-2 proposal. To get object spread you need to install separate plugins

1npm i -D babel-plugin-transform-object-rest-spread babel-plugin-syntax-object-rest-spread

and then include the plugins in your .babelrc file

1{
2  "plugins": [
3		"transform-object-rest-spread",
4		"babel-plugin-syntax-object-rest-spread"
5	]
6}

Destructing Assignment

Destructuring let’s you extract values from arrays and objects and then assign those values to distinct variables.

Objects

Here’s an object:

1let person = {
2  name: 'Aamnah',
3  age: 27,
4  status: 'Single',
5  location: 'Lahore'
6}

Now instead of doing this to reference the property values in the object

1console.info(`${person.name} is ${person.age} years old, ${person.status} and lives in ${person.location}`)

where i have to add person. with every property value to reference it out of the object (which we called person), i can destructure the object and assign the values as new variables, making it neat and easier to understand

1let { name, age, status, location } = person
2console.info(`${name} is ${age} years old, ${status} and lives in ${location}`)

We destructured the object into individual pieces and assigned those pieces to variables.

When destructuring, you don’t have to keep the variable names same as the original property names in the object, you can assign new variable names, like so:

1let { location: city } = person
2console.info(city) // Lahore

Arrays

1let widgets = ['widget1', 'widget2', 'widget3', 'widget4', 'widget5']
2let [a, b, c, ...d] = widgets
3console.log(a) // widget1
4console.log(d) // ['widget4', 'wdiget5']

Declaring default values

Destructuring is a convenient way of extracting multiple values from data stored in (possibly nested) objects and Arrays.

Template Strings/Literals ``

Template literals let us mix string literals, variables and expressions. If you have done some Python coding, template strings be very familiar.

You can now do this:

1var greeting = `Hello ${name}, how are you this fine ${partOfDay()}?`
  • To construct a template string, use the grave accent (also called a back-tick) (`) to enclose the string instead of single or double quotes.
  • Template strings provide built-in support for multi-line strings.
  • The $ character is used to specify placeholders within a template string. The syntax is ${expression}

String search methods

startsWith, endsWith and includes

 1let stringToSearch = 'really-long-string-that-i-want-to-search'
 2
 3// see if the sentence starts with 'really'
 4console.log(/^really/.test(StringToSearch)) // regex
 5console.log(stringToSearch.indexOf('really') === 0) // indexOf
 6console.log(stringToSearch.startsWith('really')) // startsWith
 7
 8// see if the sentence ends with 'to-search'
 9console.log(/to-search$/.test(stringToSearch)) // regex
10console.log(stringToSearch.indexOf('to-search') === stringToSearch.length - 'to-search'.length') // indexOf
11console.log(stringToSearch.endsWith('to-search')) // endsWith
12
13// see if the sentence includes the word 'long'
14console.log(/long/i.test(stringToSearch)) // regex
15console.log(stringToSearch.indexOf('long') > -1) // indexOf
16console.log(stringToSearch.includes('long')) // includes

Object property shorthand

In an object, if a property is defined but no value is provided, the property itself is used as value.

when the interpreter encounters a variable assignment without a property key, the variable name itself is used as property key.

1let data = { name, comments, rating }

Set

https://teamtreehouse.com/library/set https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Set A Set is not an Array but it can behave like one. It’s a collection of unique values.

The Set object lets you store unique values of any type, whether primitive values or object references.

1let mySet = new Set()

Use cases:

Map

Record

Related