Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
ECMAScript 5 (ES5P)
2.1.
ES5 features
2.2.
Advantages of ES5
2.3.
Disadvantages of ES5
3.
ECMAScript 6 (ES6)
3.1.
ES6 features
3.2.
Advantages of ES6
3.3.
Disadvantages of ES6
4.
Differences between ES5 and ES6
5.
Frequently Asked Questions
5.1.
Explain the difference between Object. freeze() vs const?
5.2.
What is a generator in JS?
5.3.
Why should we use ES6 classes?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

ES5 vs ES6

Author Shivani Singh
0 upvote

Introduction

The European Computer Manufacturers Association (ECMAScript) or (ES) is a scripting language standard that includes JavaScript, ActionScript, and JScript. It was initially designed to define JavaScript, the most popular ECMAScript implementation. The first edition of the ECMA Script was released in June 1997. ES5 and ES6 are both implemented by JavaScript. It serves as a standard for many scripting languages such as JavaScript, and JScript, as well as others. There are subtle differences between ES5 and ES6 when writing JavaScript code employing these standards.

ECMAScript 5 (ES5P)

ES5 stands for ECMAScript 5. It was released in 2009. It was the first major revision to 
JavaScript. It's a function where developers focus on how objects are created. ES5 is fully supported by all modern browsers. Here, we need to use the function keyword and return to define the function. All primitive data types supported by ES5 are String, integer, boolean, null, and undefined. Var keyword can only be used to define variables in ES5. 
Let us take a look at how to define any function in ES5

function sum(a, b) {
    return a + b;
}
sum(2, 4); //6

 

Here we use the function keyword to declare the function. 

ES5 features

  1. “use strict”: This directive declares that the JS code should be implemented in strict mode only. This gives the prevention from using any undeclared variables here.
  2. Property Getters and Setters: ES5 gives us the right to define object methods with a syntax that looks like getting or setting a property.
  3. Strings Over Multiple Lines: Multiline string literals with trailing commas and reserved words as property keys.
  4. Property Access on Strings: With the help of the charAt() method we return the character at a specified position in a string.
  5. String trim(): this method is used to remove whitespaces from both sides of the string.
  6. New Approaches: 
    Array forEach(): It is used to iterate over the elements of the collection. 
    Array reduce(): This method runs a reducer function on each array element. The reduce() method returns a single value, i.e. function’s accumulated result.
    Array some(): This method evaluates whether at least one array element passes the test implemented by the given function. It returns true if it identifies an element in the array for which the given function returns true; otherwise, it returns false.
    Array every(): This method executes a function for each array element. If the function returns true for all elements, the every() method returns true. If the function returns false for one element, the every() method returns false.
    Array.isArray(): This method determines whether the passed value is an array or not. 
    Array. prototype.indexOf(): This method returns the first index at which a given element is found in the array, and returns -1 if the element is not present.
    Array. prototype.map(): This method in JavaScript creates an array by calling a specific function on each element present in the parent array. It is a non-mutating method. 
    JSON.parse(): This method parses a JSON string, constructing the JavaScript value or object which is described by the string. 
    JSON.stringify(): When sending data to a server, it must be sent as a string. JSON.stringify() converts JavaScript data to a JSON-formatted string.

Advantages of ES5

  1. It provides a lot of browser support.
  2. It facilitates and processes the use of multiline string literals.

Disadvantages of ES5

  1. It does not have everything that ES6 has.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

ECMAScript 6 (ES6)

ES6 stands for ECMAScript 6 and was published in 2015. It is the newer version of JavaScript. Here, objects are created with the help of a new operator and an arrow function. There is no need to use the function keyword to specify the function. JavaScript data types have some new features in ES6. It introduced the 'symbol' primitive data type to allow unique values. The let and const variables are two additional ways to define variables in ES6. 
Let us take a look at how to define any function in ES6 (this is just a single example. There are many other ways to define a function in ES6).

var sum = (a, b) => {
    return a + b;
}
sum(2, 4); //6

 

Here we are using the arrow function to declare the function. It is sometimes also known as the fat arrow function.

ES6 features

  1. Arrow Function: An arrow function allows a short syntax for writing function expressions. It is defined by the '=>' syntax.
  2. Objects: Objects are instances that contain key-value pairs. ES6 makes it simple to declare objects.
  3. Classes: ES6 classes are simple to implement. They are templates for JS objects.
  4. Destructing: It facilitates pattern binding, which is essentially based on pattern matching.
  5. Interpolation of strings: With the help of this, we can make multi-line strings without using any escape characters.
  6. Default Parameters Value: ES6 allows function parameters to have default values.
  7. Symbol type: It is a primitive data type and represents a unique "hidden" identifier that no other code can accidentally access.
  8. Modules: Modules can be implemented in two ways in ES6.
  9. Map: By this, we are able to use an object as a key.
  10. New Global Methods: isFinite() and isNaN() were added.
  11. Promises: It links "Producing Code" and "Consuming Code".

Advantages of ES6

  1. The function keyword is no longer needed in ES6.
  2. The use of the return keyword is optional.
  3. Arrow function for writing functions expressions.
  4. We have import statements.
  5. Classes and objects.
  6. Easy interpolation techniques.
  7. Enhanced object literals.

Disadvantages of ES6

  1. Browser support is not as good as ES5.

Differences between ES5 and ES6

Let's examine the distinctions between ES5 and ES6 with some examples.
1. Variables
In ES5, we use the var keyword to define any variables. However, in ES6, this is not the case. Here we are using const and let keywords define the variables. Let and const utilize block scope, whereas var utilizes function scope. Also, variables specified with const are immutable.

var name = “codingninjas”; //ES5
let name = “codingninjas”; //ES6

 

Image source: ES5 vs ES6

 

2. Define objects
JS objects provide ways to define custom data types. Objects are instances that contain key-value pairs. ES6 makes it simple to declare objects.

var a = “this”;
var b = “is”;
var c = “complex”
var obj = {
    a: a,
    b: b,
    c: c
} //ES5


var a = “this”;
var b = “is”;
var c = “not”;
var d = ”complex”;
var obj = {
    a,
    b,
    c,
    d
} //ES6
Looks like its easy, isn’t it?

 

3. Merge objects
To merge objects in ES5, we use the Object.assign() function while in ES6 we use spread operator(...) as well as the Object.assign(). Spread operator does not alter the target variable, whereas Object.assign() does.

var person = {
    "name": "Ninja",
    "age": 20
};
var clothing = {
    "shoes": "sneakers",
    "shirt": "long sleeve"
};
var personWithClothes = Object.assign(person, clothing); //ES5


const person = {
    name: 'Ninja'
}
const ages = {
    age: 20
}
const merge = {
    ...person,
    ...ages
} //ES6

 

4. Object Destructuring
Objects are manually removed one by one in ES5 while in ES6, it can be done using a single line of code. It can be done in the following ways.

var clothing = {
    "shoes": "sneakers",
    "shirt": "long sleeve"
};
var shoes = clothing.shoes;
var shirt = clothing.shirt; //ES5


var {
    shoes,
    shirt
} = clothing; //ES6

Image source: object restructuring

 

5. Arrow Function
The arrow function was implemented in ES6. It allows a short syntax for writing function expressions.

const multiply = (a, b) => {
    return ab * ;
}
multiply(2, 4); //8

Image source: arrow function

 

6. String Interpolation
To combine strings in ES5, we use the concatenation operator while in ES6, template literal(`) is used for the same work.

var a = 5;
console.log("my value is  " + a + " points"); //ES5


let a = 5;
let b = 5;
console.log(`ten is ${a + b} and not ${2 * a + b}.`); //ES6


7. Importing and exporting module
Let us see how modules are imported in ES5 and ES6

module.exports = {
    something: 'value'
};
const code = require('./code');
// or
const {
    something
} = require('./code') //ES5


import code from './code'; //ES6


It's pretty simple in ES6, isn’t it?

 

Now let us see how exporting any module works in ES5 and ES6

var ESmodule = {
    console.log(“I want to understand ES5”)
}
module.exports = ESmodule; //ES5


export default ESmodule; //ES6


8. Promises and Callbacks
Dealing with asynchronous programming is made simple with Promise. A promise is something that will be fulfilled in the future. Depending on the results of the operation, a Promise can be denied or resolved. Callbacks were used to execute asynchronous programming before Promises. A callback is a mechanism to handle the execution of a function after another function has finished.
Let us see an example of Promise:

let Promise = new Promise((resolve, reject) => {
    let pro = 10;
    if (pro == 10) {
        resolve('Success');
    } else {
        reject('Failed');
    }
})
Promise.then((message) => {
            console.log("It is then block. The message is: ?+ message)  
            }).catch((message) => {
                console.log("It is Catch block. The message is: ?+ message)  
                })


Let us see how Callback works: 

function isEqual(a, b, res) {
    var same = false
    if (a = b) {
        equal = true
    }
    res(equal)
}
isEqual(1, 2, function(result) {
    if (result) {
        console.log('same');
    } else {
        console.log('not same')
    }
})

Frequently Asked Questions

Explain the difference between Object. freeze() vs const?

Const is a property that applies to bindings ("variables"). It generates an immutable bond, which means you can't change its value.
Object. freeze, on the other hand, works with values, specifically, object values. It makes an object immutable, meaning that its properties cannot be changed.

What is a generator in JS?

Generators are functions that can be exited and re-entered at a later time. Across re-entrances, their context (variable bindings) will be preserved. The function* syntax is used to write generator functions.

Why should we use ES6 classes?

We should use ES6 classes because the syntax is clearer and less prone to errors. Setting up inheritance hierarchies with the new syntax is significantly easier (and less error-prone) than with the old.

Conclusion

Eventually, we went over the fundamental differences between ES5 and ES6. We discovered what distinguishes ES5 from ES6. In terms of differences, we saw a number of examples of ES5 and ES6. Last but not least, we learned about the upsides and downsides of ES5 and ES6.

Recommended Readings:

Refer to our guided paths on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But if you have just started your learning process and looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc; you must have a look at the problemsinterview experiences, and interview bundle for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Previous article
ES6 Features
Next article
Convert Pascal Case String to Snake Case String
Live masterclass