What is ES6 (ECMAScript 6), the standard of JavaScript, and it’s features?
What is ECMAScript 6 (ES6–2015)?
First, ECMA stand for European Computer Manufacturer Association. ECMA is the association that puts out the guidelines for JavaScript in all browsers. I will cover the history of Javascript and creation of ECMA before I go into detail on ES6 features .
History
- 1995 — Javascript was created.
- 1997 — ECMAscript 1
- ECMAScript 2–3 are aboned within a few years after ES1, not as important since ES5 eclipsed the other version.
- ES4 — abandoned, sorry.
- 2009 — ES5 is released. Brought forEach, map, and filter to js.
- 2015 — ES6 specs are released
In short, ECMA(Script) is the association that provides the guidelines for what all browsers should support as well as provide new features that are available in JavaScript.
NOTE: just because new guidelines are released it does not mean that all browsers support the new features released. Compatibility Click Here.
Transpiling with Babel
Since not all browsers support ES6 you may need to transpile your code from ES6 to ES5 so your code will be read by more browsers. Transpiling is also used for CoffeeScript and TypeScript.
Babel does the transpiling in order for your browser to render appropriately. Babel is the most popular transpiler since it supports the most amount of browsers.
- Babel was created by Sebastian Mckenzie (worked at fb).
- Babel is frequently used with React which was developed by FaceBook.
Note: before you start using ES6 you may need to setup Webpack and Babel which will be required/needed to transpile ES6 back to ES5 for browser support. This is not a setup for ES6 article, but I wanted to provide the information before you get started. Some browsers may already support some ES6 features so you may not need to do much else.
ES6 Features
I will be covering new easy to adapt features within this section and provide the ES5 equivalent along with the new feature and why we should use the ES6 way.
New Variables — Const and Let
Easiest to understand are let and const, which are replacing the var
- Let — allows for block scoping which was not allowed in the past.
Previously:
var x= 20;if (x){
var x = 4;
}
console.log(x) // will output 4.
In ES5 var will update the global scope to 4.if we use let we would block scope x.let x = 20;
if (x){
let x = 4;
}
console.log(x) // output: 20
- Const — allows us to set constant variables that should not be reassigned. When you try to reassign const to a new variable it will generate an error.
const currentYear = 2018
//new year ends
var currentYear = currentYear +1Error: Uncaught SyntaxError: Identifier 'currentYear' has already been declared
Template strings
ES6 now allows you to create one single string (interpolate) rather than concatenate strings
Before ES6 we needed to do the following: let hello = "Hello, "
let person = "Roger"
Then,
let greeting = hello + person + "!!!"
//will output : "Hello, Roger!!!"Now with ES6 we can interpolate all the strings into a single one.
We need to use back ticks, which are located above the tab key and left of 1 on your keyboard.
"`".ES6:
To interpolate you will declare the variable that holds the data with a ${}. let hello = "Hello,"
let person = "Roger"let greeting = `${hello} ${person} !!! Have a great day.`
Template stringing helps with being able to add data and manipulate it easily and with less errors.
Spread Operators …
The spread operator can turn the elements of an array into arguments of a function call or into elements of an array literal.
let people = ["Roger", "Whitney", "Sarah", "Mike", "Other"]
let dogs = ["Spot","Greg", "Ben", "Spike"]
let names = ["Carl", "Bruce"]if we wanted to add people and dogs to names array, it can be done line this,
let names = ["Carl",people, "Bruce", dogs]
output: ["Carl", Array(5), "Bruce", Array(4)]
This will cause people and and dogs are a subarray.To use the spread operator we will do the following:
let names = ["Carl",...people, "Bruce", ...dogs]ES6 output: ["Carl", "Roger", "Whitney", "Sarah", "Mike", "Other", "Bruce", "Spot", "Greg", "Ben", "Spike"]
Map — one of the new type of Objects
Map holds key:value pair. You may be asking why would I want to use map instead of a new object.
A Map object can iterate its elements in insertion order — a for..of loop will return an array of [key, value] for each iteration.
- The keys of an
Object
areStrings
andSymbols
, whereas they can be any value for aMap
, including functions, objects, and any primitive. - You can get the size of a
Map
easily with thesize
property, while the number of properties in anObject
must be determined manually. - A
Map
is an iterable and can thus be directly iterated, whereas iterating over anObject
requires obtaining its keys in some fashion and iterating over them. - An
Object
has a prototype, so there are default keys in the map that could collide with your keys if you're not careful. As of ES5 this can be bypassed by usingmap = Object.create(null)
, but this is seldom done. - A
Map
may perform better in scenarios involving frequent addition and removal of key pairs.
Use objects when there is logic that operates on individual elements.
Note: this is different than .map
- Different from object, map can use something other than a string as a key.
- You can use an array, number, function, etc.
- Map can utilize key value pairs that are always the same values.
- Maps iterates in insertion order unlike object
let brand = new Map()
brand.set("Nike", {description: "for athletes"})
brand.set("Ralph Lauren", {description: "for social scenes"})console.log(brand) // Map object
console.log(brand.Nike) // undefinedIn order for map to work we need to use getconsole.log(brand.get("Nike"))//output: {description: "for athletes"}Before es6:let obj = new Object()
You can also create a new Map as so:
- It will need to be an array of arrays.
let todaysDetails = new Map([
[new Date(), "today"],
["alarms", ["8am","11pm"]
]
])//output: Map(2) {Sun Jun 17 2018 14:19:27 GMT-0400 (Eastern Daylight Time) => "today", "alarms" => Array(2)}
Sets — other type of object
What are sets?
Set
objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the Set
may only occur once; it is unique in the Set
's collection.
- The biggest difference is that data within sets has to be unique and will return unique key:value pairs only.
let tvShows = new Set()
tvShows.add("Dexter")
tvShows.add("Breaking Bad")
tvShows.add("HIMYM")console.log(tvShows)
//output : Set(3) {"Dexter", "Breaking Bad", "HIMYM"}Since we created the set we can use the .has to check if a tvShow exists.
Example: console.log("Dexter", tvShows.has("Dexter"))
//ouput: Dexter truelet data = [1,2,3,4,2]
let newSet = new Set(data)console.log(data.length)
console.log(newSet.size)
//data === 5
// newSet === 4 //removes duplicates.
Default Parameters
You are now able to assign default values similar to Ruby.
You can create a function such as:Before ES6
function addingTwoNumbers(x,y){
return x + y
}
//if we do not give any values x and y won't print out. ES6:
function addingTwoNumbers(x = 5, y = 10){
return x + y
}
// if no parameters are given it will end up with 15
Useful to avoid errors when no parameters are passed.
.repeat
.repeat is a new ES6 method. Repeat allows you to repeat a string x amount of times.
console.log("repeating".repeat(5))
//output: repeatingrepeatingrepeatingrepeatingrepeating
Could not think of why it would be useful, but it is available for use.
Connect and follow me on social media:
I am available for freelance or career opportunities, please gmail me!!