How ES6 changed JavaScript

How ES6 changed JavaScript

An overview of the features introduced in ES6

Why ES6?

ES6 is the 6th and by far the most popular version of ECMAScript. Unlike the other versions, this was a huge game-changer. It brought many features for developers to make their lives easier. It improved the syntax making it more modern and readable. Let's look at some of these changes.

Defining a variable

It is a good practice to define a variable using const simply because its value cannot be changed (although objects and arrays pointing to a const defined variable are mutable) which leaves less room for error. Using let is also a better practice to define a variable instead of var because var is vulnerable to hoisting.

//ES5
var num = 5

//ES6
const number = 5

Arrow Functions

Arrow functions is another great feature introduced in ES6. It makes the code more readable and easy to write since many functions in JavaScript use another function as a parameter.

//ES5
function add(a, b){
    return a+b
}

//ES6
const add = (a, b) => a+b

Template Literals

I am really glad that I found this feature early on, it's a real lifesaver for people like me who hate concatenation. Template literals allow a user to format a string in a more structured and readable way.

//ES5
var name = 'Chirag'
var age = 18
var message = 'Hi, my name is '+ name + ' and I am ' + age + ' years old'

//ES6
let name = 'Chirag'
let age = 18
const message = `Hi, my name is ${name} and I am {age} years old`

Destructuring

Destructuring is just the cool word for unpacking arrays and objects in JavaScript. In ES5 people had to manually assign the object/array values one by one. One can also easily swipe 2 values using this. Here's how it's done in ES6.

//Destructuring an array

//ES5
var fruits = ['apple', 'banana', 'mango']
var fruit1 = fruits[0]
var fruit2 = fruits[1]
var fruit3 = fruits[2]

//ES6
const fruits = ['apple', 'banana', 'mango']
const [fruit1, fruit2, fruit3] = fruits
//Destructuring an object

//ES5
var student = {
  name: 'Chirag',
  age: 18,
  subject: 'Compuet Science'
}

var givenName = student.name
var givenAge = student.age
var givenSubject = student.subject

//ES6
const student = {
  name: 'Chirag',
  age: 18,
  subject: 'Compuet Science'
}

const {name, age, subject} = student

Rest and Spread

I was confused about the differences between Rest and Spread operators since both use... and are quite similar in syntax. These operators have different uses. Let's see what are these uses.

A rest operator is used when the number of arguments passed into a function is unknown. ...rest is considered the best practice when using this operator but any word followed by ... can be used. All the arguments passed into the ...rest parameter are returned in a form of an array.

const print = (a,b...rest) => console.log(a,b,rest)
print(1,2,3,4,5)

A spread operator is used in many cases. ...spread destructures an array/object when passed as an argument. It can also be used to concatenate and copy arrays/objects. Here's how it is used.

numbers = [1,2,3,4,5]
Math.max(...numbers)

//Math.max(numbers) would return NaN

Classes

Classes lie at the core of object-oriented programming. Object-oriented programming is used when there are huge chunks of code. It helps keep the code more structured and readable. Here's how you create and use a class in JavaScript.

class Student{
  constructor(name,age,subject){
    this.name = name
    this.age = age
    this.subject = subject
  }
}

const student1 = new Student('Chirag', 18, 'Math')

Promises

Promises is a fantastic feature used to write asynchronous code. I have used it in fetching data from an API multiple times. It can also be used for functions that do not run immediately. Here's how you fetch data from an API using promises.

function translatetxt(){
    const query=`${apiURL}?text=${text}`
    fetch(query)                                                
    .then(response => response.json())     //promise
    .then(data => {output.innerText = data.contents.translated;})
    .catch(errorHandler)
}

Working with modules

Modules allow developers to use different pieces of code (stored in different files) in other files. This is done by using import and export. This way of writing different sections code in different files increases the readability of the program and also allows reusability. Here's how you use import and export.

// File -> main.js

export default class Student{
  constructor(name,age,subject){
    this.name = name
    this.age = age
    this.subject = subject
  }
}

export function getAge(student){
    console.log(`Student's age is ${student.age}`)

// File -> work.js

import student from /main.js  //imports class Student
import getAge as age from /main.js //imports function getAge()

Conclusion

I am pretty sure I didn't talk about all the JavaScript features introduced in the ES6 version. These were all the topics that I learned this week. I wanted to document and revise my learnings through this blog. Bonus points for me if someone found this blog helpful. If you are still here, thank you for taking out time to read my blog. I really appreciate it. Let's hope that I keep learning and keep writing more blogs!